Skip to content
intermediate Phase 16 · Adminhtml, Web API & Cron Areas

Magento 2 Cron Area

Cron area specifics - cron groups, scheduled tasks, cron configuration, and the Magento cron runner.

30m
0 problems
Topic Progress 0%

Magento Cron Architecture

Magento 2 has a built-in cron system that executes scheduled tasks. Unlike traditional crontab entries, Magento manages cron scheduling through the database and configuration files.

Cron components:

  • crontab.xml - Defines scheduled jobs per module
  • cron_groups.xml - Groups cron jobs by frequency
  • CronRunner - CLI tool that processes scheduled jobs
  • Schedule grid - Admin panel showing cron status

Cron schedule flow:

  1. System crontab triggers php bin/magento cron:run every minute
  2. cron:run reads pending schedules from cron_schedule table
  3. Jobs whose scheduled_at time has passed are executed
  4. Next execution time calculated and new schedule created
  5. Job runs via the CronRunner class

crontab.xml configuration:

<!-- app/code/Vendor/Module/etc/crontab.xml -->
<?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_module_cleanup"
             instance="Vendor\Module\Cron\Cleanup"
             method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

Cron expressions follow standard format: {minute} {hour} {day} {month} {weekday}

Examples:

  • * * * * * - Every minute
  • 0 */2 * * * - Every 2 hours
  • 30 2 * * * - Daily at 2:30 AM
  • 0 0 * * 0 - Weekly on Sunday at midnight

Cron Job Implementation

Cron job classes implement a simple interface with an execute() method.

<?php
namespace Vendor\Module\Cron;

use Psr\Log\LoggerInterface;

class Cleanup
{
    private $logger;
    private $itemRepository;
    
    public function __construct(
        LoggerInterface $logger,
        \Vendor\Module\Api\ItemRepositoryInterface $itemRepository
    ) {
        $this->logger = $logger;
        $this->itemRepository = $itemRepository;
    }
    
    public function execute(): void
    {
        $this->logger->info('Starting vendor module cleanup cron job');
        
        try {
            $this->removeExpiredItems();
            $this->logger->info('Cleanup completed successfully');
        } catch (\Exception $e) {
            $this->logger->error('Cleanup failed: ' . $e->getMessage());
        }
    }
    
    private function removeExpiredItems(): void
    {
        // Implementation logic
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter('expires_at', date('Y-m-d H:i:s'), 'lt')
            ->create();
        
        $items = $this->itemRepository->getList($searchCriteria);
        foreach ($items->getItems() as $item) {
            $this->itemRepository->delete($item);
        }
    }
}

Cron groups for different frequencies:

<!-- app/code/Vendor/Module/etc/cron_groups.xml -->
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/cron_groups.xsd">
    <group id="vendor_heavy">
        <schedule_generate_every>15</schedule_generate_every>
        <schedule_ahead_for>20</schedule_ahead_for>
        <schedule_lifetime>15</schedule_lifetime>
        <history_cleanup_every>10080</history_cleanup_every>
        <history_success_lifetime>10080</history_success_lifetime>
        <history_failure_lifetime>10080</history_failure_lifetime>
    </group>
</config>

Run specific cron group:

php bin/magento cron:run --group=vendor_heavy

Cron Monitoring and Debugging

Magento provides several tools for monitoring and debugging cron jobs.

Check cron schedule in database:

SELECT * FROM cron_schedule 
WHERE job_code LIKE 'vendor_module%' 
ORDER BY scheduled_at DESC 
LIMIT 20;

Status codes:

  • pending - Scheduled but not yet executed
  • running - Currently executing
  • success - Completed without errors
  • error - Failed with exception
  • missed - Scheduled time passed without execution

Debug cron execution:

// Enable cron logging in di.xml
<config>
    <type name="Magento\Cron\Model\Cron">
        <arguments>
            <argument name="logger" xsi:type="object">
                Vendor\Module\Logger\CronLogger
            </argument>
        </arguments>
    </type>
</config>

View cron output in admin:
Navigate to System → Cron Schedule to see the status grid of all cron jobs.

Programmatic schedule management:

$schedule = $this->scheduleFactory->create();
$schedule->setJobCode('vendor_module_cleanup')
    ->setSchedule('* * * * *')
    ->setStatus('pending')
    ->setCreatedAt(date('Y-m-d H:i:s'));
$this->scheduleResource->save($schedule);

CLI commands:

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

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

# View cron history
php bin/magento cron:run --job=vendor_module_cleanup

Quiz

1. How often does Magento's cron:run command check for pending schedules?

Question 1 options

2. What does the 'missed' status mean in cron_schedule?

Question 2 options

3. Which XML file defines cron job schedules in a module?

Question 3 options

Flashcards

Question

What CLI command runs Magento cron jobs?

Answer

php bin/magento cron:run

Question

What does a cron expression like '0 */2 * * *' mean?

Answer

Every 2 hours at minute 0

Question

Where are cron schedules stored?

Answer

In the cron_schedule database table

Question

How do you run a specific cron group?

Answer

php bin/magento cron:run --group={group_name}

Revision Notes

Key Takeaways

  • 1. Magento cron uses database-backed scheduling, not just system crontab
  • 2. Jobs defined in etc/crontab.xml with cron expressions
  • 3. Cron groups allow different execution frequencies
  • 4. cron:run should execute every minute via system crontab
  • 5. Schedule statuses: pending, running, success, error, missed
  • 6. Monitor via admin grid or cron_schedule database table

Interview Tips

  • Explain the difference between Magento cron and system crontab
  • Describe how to create a custom cron job with proper logging
  • Discuss cron groups and when to use separate groups
  • Explain how to debug failed cron jobs
  • Know the cron_schedule table structure and statuses

Cheat Sheet

Cron Area Cheat Sheet

Job Config: etc/crontab.xml
Group Config: etc/cron_groups.xml
Table: cron_schedule

Expression Format: {min} {hour} {day} {month} {weekday}

Common Patterns:

  • * * * * * - Every minute
  • 0 2 * * * - Daily at 2 AM
  • */15 * * * * - Every 15 minutes

CLI Commands:

php bin/magento cron:run
php bin/magento cron:run --group=default

Status Values: pending → running → success/error/missed