Skip to content
intermediate Phase 65 · Cron System

Scheduling Cron Jobs — Expressions and Schedule Management

Scheduling cron jobs in Magento 2: cron expression syntax, schedule management, missed schedule handling, and cron job configuration

45m
1 problems
Topic Progress 0%

Cron Expression Syntax

Five-Field Format

┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-6, Sunday=0)
│ │ │ │ │
* * * * *

Special Characters

Character Meaning Example
* Any value * * * * * = every minute
, List 1,3,5 = Monday, Wednesday, Friday
- Range 1-5 = Monday through Friday
/ Step */5 = every 5 units

Common Expressions

* * * * *           Every minute
*/5 * * * *         Every 5 minutes
0 * * * *           Every hour at :00
0 0 * * *           Daily at midnight
0 2 * * *           Daily at 2:00 AM
0 0 * * 0           Every Sunday at midnight
0 0 1 * *           First of every month
*/15 * * * *        Every 15 minutes
0 9-17 * * *        Every hour 9AM-5PM
0 0 * * 1-5         Weekdays at midnight
0 0 1,15 * *        1st and 15th of month

Practical Examples

<!-- Every 5 minutes -->
<schedule>*/5 * * * *</schedule>

<!-- Every hour during business hours (9-17) -->
<schedule>0 9-17 * * *</schedule>

<!-- Daily cleanup at 3 AM -->
<schedule>0 3 * * *</schedule>

<!-- Weekly report on Sunday -->
<schedule>0 0 * * 0</schedule>

<!-- Monthly maintenance -->
<schedule>0 0 1 * *</schedule>

Config-Based Schedules

Using config_path

Allow store admins to configure schedules via admin panel:

<job name="vendor_sync" instance="Vendor\Cron\Sync" method="execute">
    <schedule config_path="vendor_module/cron/schedule"/>
</job>

Defining Default in config.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <vendor_module>
            <cron>
                <schedule>*/10 * * * *</schedule>
            </cron>
        </vendor_module>
    </default>
</config>

Admin Configuration

Create admin system.xml for schedule configuration:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <section id="vendor_module">
            <group id="cron">
                <field id="schedule" type="text">
                    <label>Cron Schedule</label>
                </field>
            </group>
        </section>
    </system>
</config>

Benefits of Config-Based Schedules

  • Store admins can adjust without code changes
  • Different schedules per environment
  • Easy to change in production

Missed Schedule Handling

What is a Missed Schedule?

A schedule is marked as missed when:

  1. The scheduled time has passed
  2. The job was not executed
  3. The schedule_lifetime has expired
SELECT * FROM cron_schedule
WHERE status = 'missed'
ORDER BY scheduled_at DESC;

Common Causes

  • System cron not running
  • Job taking longer than schedule_lifetime
  • Schedule generation interval too large
  • Server downtime

Handling Missed Schedules

namespace Vendor\Module\Cron;

class Cleanup
{
    public function execute(): void
    {
        // Check if there are pending items that need processing
        $pendingItems = $this->getPendingItems();
        
        if (empty($pendingItems)) {
            return; // Nothing to do
        }
        
        foreach ($pendingItems as $item) {
            $this->processItem($item);
        }
    }
}

Cleanup Missed Schedules

-- Delete old missed schedules
DELETE FROM cron_schedule
WHERE status = 'missed'
AND scheduled_at < DATE_SUB(NOW(), INTERVAL 7 DAY);

-- Or configure in cron_groups.xml
<history_success_lifetime>60</history_success_lifetime>
<history_failure_lifetime>480</history_failure_lifetime>

Preventing Missed Schedules

<!-- Reduce schedule generation interval -->
<schedule_generate_every>5</schedule_generate_every>

<!-- Extend schedule validity -->
<schedule_lifetime>30</schedule_lifetime>

<!-- Ensure adequate time between runs -->
<schedule>0 */2 * * *</schedule>  <!-- Every 2 hours -->

Schedule Management

Viewing Schedules

-- All pending schedules
SELECT * FROM cron_schedule
WHERE status = 'pending'
AND scheduled_at > NOW()
ORDER BY scheduled_at;

-- Schedules for specific job
SELECT * FROM cron_schedule
WHERE job_code = 'vendor_product_sync'
ORDER BY scheduled_at DESC
LIMIT 20;

-- Execution duration
SELECT
    job_code,
    scheduled_at,
    executed_at,
    finished_at,
    TIMESTAMPDIFF(SECOND, executed_at, finished_at) as duration_sec
FROM cron_schedule
WHERE status = 'success'
ORDER BY executed_at DESC
LIMIT 50;

Schedule Summary Dashboard

SELECT
    job_code,
    COUNT(*) as total_runs,
    SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as successes,
    SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as failures,
    SUM(CASE WHEN status = 'missed' THEN 1 ELSE 0 END) as missed,
    AVG(TIMESTAMPDIFF(SECOND, executed_at, finished_at)) as avg_duration
FROM cron_schedule
WHERE executed_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)
GROUP BY job_code
ORDER BY total_runs DESC;

Common Schedule Patterns

Pattern Use Case
*/5 * * * * Frequent checks (inventory, stock)
0 * * * * Hourly tasks (currency, reports)
0 0 * * * Daily cleanup, backups
0 0 * * 0 Weekly reports, maintenance
0 0 1 * * Monthly tasks, archiving

Practice Problems

0 / 1 solved
Missed Schedule Investigation

A cron job shows 'missed' status for the past week. Identify the root cause and fix it.

Quiz

1. What cron expression runs a job every 15 minutes?

Question 1 options

2. How can you make a cron schedule configurable via admin?

Question 2 options

3. What happens when a schedule exceeds schedule_lifetime?

Question 3 options

4. What does 0 0 * * 1-5 mean?

Question 4 options

Flashcards

Question

What does */5 * * * * mean?

Answer

Every 5 minutes

Question

What does 0 0 * * 0 mean?

Answer

Every Sunday at midnight

Question

How to make schedule admin-configurable?

Answer

Use config_path in crontab.xml with default in config.xml

Question

What is a missed schedule?

Answer

A schedule that was not executed before schedule_lifetime expired

Question

What does 0 2 * * * mean?

Answer

Every day at 2:00 AM

Revision Notes

Key Takeaways

  • 1. Cron expressions use 5-field format: minute, hour, day, month, weekday
  • 2. Special characters: * (any), , (list), - (range), / (step)
  • 3. Use config_path for admin-configurable schedules
  • 4. Missed schedules occur when schedule_lifetime expires
  • 5. Reduce schedule_generate_every and increase schedule_lifetime to prevent misses
  • 6. Monitor schedules with SQL queries on cron_schedule table

Interview Tips

  • Write cron expressions for common intervals
  • Explain config_path pattern for admin-configurable schedules
  • Discuss causes and fixes for missed schedules
  • Describe schedule management best practices

Cheat Sheet

Scheduling Cheat Sheet

Common expressions:

  • */5 * * * * = every 5 min
  • 0 * * * * = every hour
  • 0 0 * * * = daily midnight
  • 0 0 * * 0 = weekly Sunday
  • 0 0 1 * * = monthly 1st

Config schedule:

<schedule config_path="vendor/cron/schedule"/>

Missed schedule:

  • Cause: schedule_lifetime expired
  • Fix: reduce generate_every, increase lifetime

Monitor:
SELECT * FROM cron_schedule WHERE status = 'missed'