How to work Cron functionality in Magento 2

logo logo

Learn how Magento 2’s cron mechanism uses crontab.xml to control the scheduling of background tasks.

If you’ve used Magento 2, you’re likely aware that many essential operations are handled automatically through scheduled tasks. These recurring tasks, managed by Magento’s built-in cron system, help maintain the store’s performance by automating functions such as indexing, email dispatch, and cache cleanup.

However, understanding how these scheduled tasks actually function within Magento can be more complex than initially appears. To effectively set up and manage cron jobs, it’s crucial to first grasp the fundamentals of how cron scheduling works in Magento 2. This includes familiarizing yourself with core concepts like cron expressions, job execution timing, and the way Magento orchestrates these tasks behind the scenes. By understanding the various components and terminology involved, you’ll be better equipped to configure, troubleshoot, and optimize scheduled operations within Magento’s framework, ensuring your store runs smoothly and efficiently.

How do cron, crontab, and cron jobs differ in their functions and roles?

  • A cron job is a background service that operates on the server, executing scheduled commands outlined in a crontab configuration.
  • Crontab is the configuration file used by the cron system to schedule recurring tasks. The name stands for ‘cron table’. Each line in a crontab defines a job and the time it should run, using a cron expression like * * * * *. Tools like Cron Guru help explain how these expressions work.
  • A cron job refers to a single scheduled task specified within a crontab file. A crontab can contain one or multiple cron jobs.

In what ways does Cron integrate with and function within Magento?

Standard PHP setups usually involve configuring several cron jobs within one crontab file, each scheduled using a specific cron expression. Here’s an example of a crontab file that specifies two separate cron jobs:


/etc/crontab
# Run a PHP script every weekday at 6:15 AM 
15 6 * * 1-5 /usr/bin/php /var/www/html/send_reports.php
# Run another PHP script every hour on the hour
0 * * * * /usr/bin/php /var/www/html/update_stats.php

In Magento, the approach to scheduled tasks differs somewhat. Managing numerous cron jobs for various modules directly within a crontab file can become unwieldy, since this file is maintained outside of Magento’s core system. As a result, it isn’t integrated into version control, making it challenging to coordinate across different environments.

Therefore, a common alternative is to set up a single, unified cron job for Magento that operates consistently across all environments. This job typically executes a script like the following:


/etc/crontab
* * * * * /usr/bin/php /var/www/html/bin/magento cron:run 2>&1 | grep -v "Ran jobs by schedule" >> /var/www/html/var/log/magento.cron.log

The command above runs the bin/magento cron:run script once every minute, as set by the * * * * schedule. After the command runs, its output is sorted and then saved to the file located at /var/log/magento.cron.log.

This indicates that the handling and execution of scheduled jobs in Magento are entirely controlled through Magento’s `cron:run` command. Every minute, the `bin/magento cron:run` command is triggered, which subsequently invokes Magento’s built-in PHP script to perform the scheduled tasks.

Setting up cron jobs in Magento:

Magento has its own built-in system to handle scheduled tasks, called cron jobs, which keep everything running smoothly like updating products or sending emails. Developers can add their own tasks to this system easily. Instead of writing a regular crontab file like on a Unix server, Magento uses a simple XML file to set up and manage these scheduled jobs, making it easy to control what runs and when within the system.

Why is the crontab.xml file used?

The goal of the crontab.xml file is to define the key information for each scheduled task:

Job Name: The unique name you give to the cron job so Magento can tell it apart from others.

Schedule: How often the job runs, described using cron’s special timing format.

Run Model: The code (class and method) that runs when the job starts.

This file is located inside the etc/crontab.xml directory of a Magento module and typically looks like the following example:


etc/crontab.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/crontab.xsd">
  <group id="default">
    <job name="my_custom_cron_job" instance="Vendor\Module\Cron\MyJob" method="execute">
      <schedule>*/5 * * * *</schedule> <!-- Every 5 minutes -->
    </job>
  </group>
</config>

Essentially, we are specifying the class instance that manages this cron job along with the method that will be invoked.

What are Cron groups in Magento?

In Magento 2, Cron groups are a way to organize and manage scheduled tasks (cron jobs) by grouping related cron configurations together. Each cron group corresponds to a specific set of scheduled tasks that can be configured independently, allowing for better control and segmentation of cron executions.

Key points about Cron groups:

Defined in etc/crontab.xml: Each module can specify one or more cron groups within this configuration file.

Configuration options: For each group, you can define properties such as the schedule, the class and method to execute, and the execution frequency.

Default group: Magento has a default cron group called default, but you can create custom groups (e.g., index, emails, etc.) for different types of scheduled tasks.

Separation of concerns: By organizing cron jobs into groups, you can run specific sets of tasks independently, which enhances flexibility and performance management.


<group id="my_custom_group" schedule="0 2 * * *">  
<job name="my_custom_job" instance="Vendor\Module\Cron\MyJob" method="execute"/>
</group>
  • <group id=”my_custom_group” schedule=”0 2 * * *”>
    • <group>: Defines a cron group, which is a collection of scheduled jobs.
    • id=”my_custom_group”: The unique identifier for this cron group. You can have multiple groups for different categories of tasks.
    • schedule=”0 2 * * *”: The schedule expression in cron format, indicating when the jobs in this group should run.
      • This specific cron expression means 2:00 AM every day.
      • Format: minute hour day_of_month month day_of_week
  • <job name=”my_custom_job” instance=”Vendor\Module\Cron\MyJob” method=”execute”/>
    • <job>: Defines a specific scheduled task within the group.
    • name=”my_custom_job”: An identifier for this job.
    • instance=”Vendor\Module\Cron\MyJob”: The PHP class that contains the logic to execute.
      • This class should implement a method named execute().
    • method=”execute”: The method within the class that will be called when the cron job runs.

What does it do by `bin/magento cron:run –group=foo`?

It manually executes all scheduled cron jobs that belong to the `foo` group. This command is useful for testing or running specific sets of cron tasks outside the regular schedule.

  • bin/magento: The CLI tool used to interact with Magento.
  • cron:run: The command to execute scheduled cron jobs.
  • –group=foo: Specifies which cron group to run. Only jobs assigned to the foo group will be executed.

How crontab.xml Works with the cron_schedule Table in Magento?

Although the cron:run command is typically executed every minute (often configured via the system crontab or bin/magento cron:install), the actual scheduling of specific tasks is controlled by Magento’s own cron system.

The crontab.xml file defines what and when.

The cron_schedule table keeps track of execution history and state.

The cron:run command acts as the orchestrator, checking crontab definitions and managing scheduled job execution through the database.

Each row in cron_schedule table represents a specific instance of a cron job (with job_code, status, scheduled_at, etc.). This table ensures that jobs are not re-scheduled if already pending or running. It tracks when jobs were executed (executed_at) and whether they succeeded or failed.

Regarding Job Execution, Magento then looks at the cron_schedule table for any entries marked as pending and attempts to run them. Upon completion:

  • status is updated to success or error
  • messages, executed_at, and finished_at are updated accordingly

Purpose of cron_schedule Table:

The cron_schedule table in Magento is a core database table used to manage and track scheduled tasks (cron jobs) within the system. It stores information about each scheduled task, including its status, execution times, and related details.

The cron_schedule table contains the following columns based on the latest version of Magento:

Column Name Data Type Description
schedule_id Int Primary key (auto-increment ID of the cron entry)
job_code varchar (255) The identifier for the cron job (e.g. indexer_reindex_all_invalid)
status varchar (16) Status of the cron job (e.g. pending, running, success, missed, error)
messages text Log or error messages generated during execution
created_at timestamp When the cron job entry was created
scheduled_at timestamp When the cron job was scheduled to run
executed_at timestamp (nullable) When the cron job started
finished_at timestamp (nullable) When the cron job finished

When Magento’s cron system executes, it checks the cron_schedule table for any jobs with a status of pending and runs them according to their designated scheduled times.

The cron_schedule table in Magento is critical for managing and tracking scheduled (cron) jobs. This table is part of Magento’s built-in cron system, which is used to automate tasks like reindexing, sending emails, generating sitemaps, and more.

In summary, Magento 2’s cron system is a robust and essential component for automating routine tasks across the platform. Gaining a clear understanding of how crontab.xml job definitions translate into scheduled tasks within the cron_schedule database table, empowers developers to create reliable cron jobs, monitor their execution, and troubleshoot issues more efficiently. Mastering this workflow is key to maintaining a healthy and scalable Magento application.

Author Image

Rajesh Prajapati

Rajesh Prajapati is a talented Senior Web Developer at Aims Infosoft, contributing his expertise to deliver high‑quality, robust, and scalable web solutions for our clients. He plays a key role in turning client requirements into functional, user‑friendly applications. His focus on clean code, best practices, and attention to detail helps ensure every project meets our high standards of quality.

Related Posts

A Word From Our Proud Clients

See what our most successful clients have to say about working with us...