Skip to content
intermediate Phase 65 · Cron System

Cron Introduction — Scheduled Tasks in Magento 2

Understanding what cron is, how Magento runs scheduled tasks, crontab.xml configuration, and cron groups in Magento 2

45m
1 problems
Topic Progress 0%

What is Cron?

System Cron

Cron is a time-based job scheduler in Unix/Linux systems. It runs tasks at specified intervals without manual intervention.

# System crontab (every minute)
* * * * * php /var/www/html/bin/magento cron:run

Magento Cron Runner

Magento extends system cron with its own cron runner:

  1. System cron calls bin/magento cron:run every minute
  2. Magento checks cron_schedule table for pending jobs
  3. Jobs matching the current time are executed
  4. Job status is recorded in cron_schedule

Why Cron in Magento?

  • Reindexing catalog data
  • Sending email queues
  • Cleaning logs and temporary data
  • Updating currency rates
  • Processing message queue consumers
  • Sending newsletters and reminders
  • Updating product prices and stock

crontab.xml Configuration

Basic Structure

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="vendor_product_sync"
             instance="Vendor\Module\Cron\ProductSync"
             method="execute">
            <schedule>*/5 * * * *</schedule>
        </job>
    </group>
</config>

Job Attributes

Attribute Description
name Unique job identifier
instance PHP class implementing the cron job
method Method to call (usually execute)

Schedule Options

<!-- Direct cron expression -->
<schedule>* * * * *</schedule>

<!-- Config-based schedule -->
<schedule config_path="vendor_module/cron/schedule"/>

Multiple Jobs

<group id="default">
    <job name="sync" instance="Vendor\Cron\Sync" method="execute">
        <schedule>*/5 * * * *</schedule>
    </job>
    <job name="cleanup" instance="Vendor\Cron\Cleanup" method="execute">
        <schedule>0 2 * * *</schedule>
    </job>
    <job name="report" instance="Vendor\Cron\Report" method="execute">
        <schedule>0 0 * * 0</schedule>
    </job>
</group>

Cron Job Implementation

Basic Cron Job Class

namespace Vendor\Module\Cron;

use Psr\Log\LoggerInterface;

class ProductSync
{
    public function __construct(
        private LoggerInterface $logger
    ) {}

    public function execute(): void
    {
        $this->logger->info('Product sync started');
        try {
            $this->syncProducts();
            $this->logger->info('Product sync completed');
        } catch (\Exception $e) {
            $this->logger->error('Sync failed: ' . $e->getMessage());
        }
    }
}

With Dependencies

namespace Vendor\Module\Cron;

use Magento\Framework\App\State\AreaCode;
use Vendor\Module\Service\SyncService;

class ProductSync
{
    public function __construct(
        private AreaCode $areaCode,
        private SyncService $syncService
    ) {}

    public function execute(): void
    {
        $this->areaCode->setAreaCode(AreaCode::AREA_GLOBAL);
        $this->syncService->syncAllProducts();
    }
}

Running Cron Manually

# Run all cron jobs
php bin/magento cron:run

# Run specific group
php bin/magento cron:run --group default

# Check cron status
php bin/magento cron:status

Cron Schedule Table

cron_schedule Table

All scheduled jobs are tracked in the cron_schedule table:

CREATE TABLE cron_schedule (
    schedule_id INT UNSIGNED AUTO_INCREMENT,
    job_code VARCHAR(255),
    status VARCHAR(7), -- pending, running, success, error, missed
    messages TEXT,
    created_at TIMESTAMP,
    scheduled_at TIMESTAMP,
    executed_at TIMESTAMP,
    finished_at TIMESTAMP
);

Common Queries

-- Check pending jobs
SELECT * FROM cron_schedule WHERE status = 'pending' ORDER BY scheduled_at;

-- Check failed jobs
SELECT * FROM cron_schedule WHERE status = 'error' ORDER BY executed_at DESC LIMIT 10;

-- Check job history
SELECT job_code, status, executed_at, finished_at
FROM cron_schedule
WHERE job_code = 'vendor_product_sync'
ORDER BY executed_at DESC LIMIT 20;

-- Find missed jobs
SELECT * FROM cron_schedule WHERE status = 'missed';

Schedule Generation

Magento generates future schedules based on cron expressions. The schedule_generate_every setting controls how often new schedules are created.

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

Practice Problems

0 / 1 solved
Cron Job Not Running

A cron job is configured in crontab.xml but never executes. Diagnose the issue.

Quiz

1. What table stores Magento cron schedules?

Question 1 options

2. What command runs all Magento cron jobs?

Question 2 options

3. What XML file declares cron jobs?

Question 3 options

4. What is the default cron group?

Question 4 options

Flashcards

Question

What is the Magento cron runner?

Answer

A process that checks cron_schedule table and executes pending jobs at scheduled times

Question

What file declares cron jobs?

Answer

crontab.xml in the module's etc/ directory

Question

What table stores cron job schedules?

Answer

cron_schedule with columns for status, scheduled_at, executed_at

Question

How to run cron manually?

Answer

php bin/magento cron:run [--group groupname]

Question

What are common cron job statuses?

Answer

pending, running, success, error, missed

Revision Notes

Key Takeaways

  • 1. Cron is a time-based scheduler; Magento extends it with cron:run
  • 2. crontab.xml declares jobs with cron expression schedules
  • 3. Cron groups organize jobs and control execution settings
  • 4. cron_schedule table tracks all job executions and statuses
  • 5. Run cron manually with php bin/magento cron:run
  • 6. Common statuses: pending, running, success, error, missed

Interview Tips

  • Explain how Magento cron differs from system cron
  • Describe the cron_schedule table and its columns
  • Discuss cron groups and why they exist
  • Know how to debug a cron job that is not running

Cheat Sheet

Cron Introduction Cheat Sheet

Flow:
System cron -> cron:run -> Check cron_schedule -> Execute pending jobs

crontab.xml:

<group id="default">
  <job name="job" instance="Class" method="execute">
    <schedule>*/5 * * * *</schedule>
  </job>
</group>

CLI:
cron:run, cron:run --group, cron:status

Table: cron_schedule (schedule_id, job_code, status, scheduled_at, executed_at)

Statuses: pending, running, success, error, missed