Configure a custom cron job

This step-by-step tutorial shows how to create a custom cron job and optionally a cron group in a sample module. You can use a module you already have or you can use a sample module from our magento2-samples repository.

Running the cron job results in a row being added to the cron_schedule table with the name of the cron job, custom_cron.

We also show you how to optionally create a cron group, which you can use to run custom cron jobs with settings other than Commerce application defaults.

In this tutorial, we assume the following:

  • The Commerce application is installed in /var/www/html/magento2
  • Your Commerce database username and password are both magento
  • You perform all actions as the file system owner

Step 1: Get a sample module

To set up a custom cron job, you need a sample module. We suggest the magento-module-minimal module.

If you already have a sample module, you can use it; skip this step and the next step and continue with Step 3: Create a class to run cron.

To get a sample module:

  1. Log in to your Commerce server as, or switch to, the file system owner.

  2. Change to a directory that is not in your Commerce application root (for example, your home directory).

  3. Clone the magento2-samples repository.

    code language-bash
    git clone git@github.com:magento/magento2-samples.git
    

    If the command fails with the error Permission denied (publickey)., you must add your SSH public key to GitHub.com.

  4. Make a directory to which to copy the sample code:

    code language-bash
    mkdir -p /var/www/html/magento2/app/code/Magento/SampleMinimal
    
  5. Copy the sample module code:

    code language-bash
    cp -r ~/magento2-samples/sample-module-minimal/* /var/www/html/magento2/app/code/Magento/SampleMinimal
    
  6. Verify the files copied properly:

    code language-bash
    ls -al /var/www/html/magento2/app/code/Magento/SampleMinimal
    

    You should see the following result:

    code language-terminal
    drwxrwsr-x.   4 magento_user apache  4096 Oct 30 13:19 .
    drwxrwsr-x. 121 magento_user apache  4096 Oct 30 13:19 ..
    -rw-rw-r--.   1 magento_user apache   372 Oct 30 13:19 composer.json
    drwxrwsr-x.   2 magento_user apache  4096 Oct 30 13:19 etc
    -rw-rw-r--.   1 magento_user apache 10376 Oct 30 13:19 LICENSE_AFL.txt
    -rw-rw-r--.   1 magento_user apache 10364 Oct 30 13:19 LICENSE.txt
    -rw-rw-r--.   1 magento_user apache  1157 Oct 30 13:19 README.md
    -rw-rw-r--.   1 magento_user apache   270 Oct 30 13:19 registration.php
    drwxrwsr-x.   3 magento_user apache  4096 Oct 30 13:19 Test
    
  7. Update the Commerce database and schema:

    code language-bash
    bin/magento setup:upgrade
    
  8. Clean the cache:

    code language-bash
    bin/magento cache:clean
    

Step 2: Verify the sample module

Before you continue, verify that the sample module is registered and enabled.

  1. Run the following command:

    code language-bash
    bin/magento module:status Magento_SampleMinimal
    
  2. Make sure that the module is enabled.

    code language-terminal
    Module is enabled
    
TIP
If the output indicates that the Module does not exist, review Step 1 carefully. Make sure your code is in the correct directory. Spelling and case are important; if anything is different, the module will not load. Also, do not forget to run magento setup:upgrade.

Step 3: Create a class to run cron

This step shows a simple class to create a cron job. The class only writes a row to the cron_schedule table that confirms it is set up successfully.

To create a class:

  1. Create a directory for the class and change to that directory:

    code language-bash
    mkdir /var/www/html/magento2/app/code/Magento/SampleMinimal/Cron && cd /var/www/html/magento2/app/code/Magento/SampleMinimal/Cron
    
  2. Created a file named Test.php in that directory with the following contents:

    code language-php
    <?php
    namespace Magento\SampleMinimal\Cron;
    
    use Psr\Log\LoggerInterface;
    
    class Test {
        protected $logger;
    
        public function __construct(LoggerInterface $logger) {
            $this->logger = $logger;
        }
    
       /**
        * Write to system.log
        *
        * @return void
        */
        public function execute() {
            $this->logger->info('Cron Works');
        }
    }
    

Step 4: Create crontab.xml

The crontab.xml file sets a schedule to run your custom cron code.

Create crontab.xml as follows in the /var/www/html/magento2/app/code/Magento/SampleMinimal/etc directory:

<?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="custom_cronjob" instance="Magento\SampleMinimal\Cron\Test" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

The preceding crontab.xml runs the Magento/SampleMinimal/Cron/Test.php class once per minute, resulting in a row being added to the cron_schedule table.

In order to make the cron schedule configurable from the Admin, use the configuration path of your system configuration field.

<?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="custom_cronjob" instance="Magento\SampleMinimal\Cron\Test" method="execute">
            <config_path>system/config/path</config_path>
        </job>
    </group>
</config>

Where, system/config/path is a system configuration path defined in etc/adminhtml/system.xml of a module.

Step 5: Compile and cache clean

Compile the code with this command:

bin/magento setup:di:compile

And clean the cache with this command:

bin/magento cache:clean

Step 6: Verify the cron job

This step shows how to verify the custom cron job successfully using a SQL query on the cron_schedule database table.

To verify cron:

  1. Run Commerce cron jobs:

    code language-bash
    bin/magento cron:run
    
  2. Enter the magento cron:run command two or three times.

    The first time you enter the command, it queues jobs; subsequently, the cron jobs are run. You must enter the command at least twice.

  3. Run the SQL query SELECT * from cron_schedule WHERE job_code like '%custom%' as follows:

    1. Enter mysql -u magento -p

    2. At the mysql> prompt, enter use magento;

    3. Enter SELECT * from cron_schedule WHERE job_code like '%custom%';

      The result should be similar to the following:

      code language-terminal
      +-------------+----------------+---------+----------+---------------------+---------------------+---------------------+---------------------+
      | schedule_id | job_code       | status  | messages | created_at        | scheduled_at        | executed_at         | finished_at     |
      +-------------+----------------+---------+----------+---------------------+---------------------+---------------------+---------------------+
      |        3670 | custom_cronjob | success | NULL     | 2016-11-02 09:38:03 | 2016-11-02 09:38:00 | 2016-11-02 09:39:03 | 2016-11-02 09:39:03 |
      |        3715 | custom_cronjob | success | NULL     | 2016-11-02 09:53:03 | 2016-11-02 09:53:00 | 2016-11-02 09:54:04 | 2016-11-02 09:54:04 |
      |        3758 | custom_cronjob | success | NULL     | 2016-11-02 10:09:03 | 2016-11-02 10:09:00 | 2016-11-02 10:10:03 | 2016-11-02 10:10:03 |
      |        3797 | custom_cronjob | success | NULL     | 2016-11-02 10:24:03 | 2016-11-02 10:24:00 | 2016-11-02 10:25:03 | 2016-11-02 10:25:03 |
      +-------------+----------------+---------+----------+---------------------+---------------------+---------------------+---------------------+
      
  4. (Optional) Verify that messages are written to Commerce’s system log:

    code language-bash
    cat /var/www/html/magento2/var/log/system.log
    

    You should see one or more entries like the following:

    code language-terminal
    [2016-11-02 22:17:03] main.INFO: Cron Works [] []
    

    These messages come from the execute method in Test.php:

    code language-php
    public function execute() {
         $this->logger->info('Cron Works');
    

If the SQL command and system log contain no entries, run the magento cron:run command a few more times and wait. It can take some time for the database to update.

Step 7 (optional): Set up a custom cron group

This step shows how to optionally set up a custom cron group. You should set up a custom cron group if you want your custom cron job to run on a different schedule than other cron jobs (typically, once per minute) or if you want several custom cron jobs to run with different settings.

To set up a custom cron group:

  1. Open crontab.xml in a text editor.

  2. Change <group id="default"> to <group id="custom_crongroup">

  3. Exit the text editor.

  4. Create /var/www/html/magento2/app/code/Magento/SampleMinimal/etc/cron_groups.xml with the following contents:

    code language-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="custom_crongroup">
            <schedule_generate_every>1</schedule_generate_every>
            <schedule_ahead_for>4</schedule_ahead_for>
            <schedule_lifetime>2</schedule_lifetime>
            <history_cleanup_every>10</history_cleanup_every>
            <history_success_lifetime>60</history_success_lifetime>
            <history_failure_lifetime>600</history_failure_lifetime>
            <use_separate_process>1</use_separate_process>
        </group>
    </config>
    

For a description of what the options mean, see Customizing crons reference.

Step 8: Verify your custom cron group

This optional step shows how to verify your custom cron group using the Admin.

To verify your custom cron group:

  1. Run Commerce cron jobs for your custom group:

    code language-bash
    php /var/www/html/magento2/bin/magento cron:run --group="custom_crongroup"
    

    Run the command at least twice.

  2. Clean the cache:

    code language-bash
    php /var/www/html/magento2/bin/magento cache:clean
    
  3. Log in to the Admin as an administrator.

  4. Click Stores > Settings > Configuration > Advanced > System.

  5. In the right pane, expand Cron.

    Your cron group displays as follows:

    Your custom cron group

recommendation-more-help
386822bd-e32c-40a8-81c2-ed90ad1e198c