Config and run cron job

Magento 2: How to config and run cron jobs

Magento 2 is not able to work well without Cron Jobs configured properly.
It helps re-index your store, send emails, notify customers or any jobs defined by 3rd party extensions.

Checking catalog rule module from Magento 2 at vendor/magento/module-catalog-rule/etc/crontab.xml, we can see a cron job defined as below

<config xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="catalogrule_apply_all" instance="Magento\CatalogRule\Cron\DailyCatalogUpdate" method="execute">
            <schedule>0 1 * * *</schedule>
        </job>
    </group>
</config>

To run these jobs, we must config Linux crontab

crontab -l #to check current configured cron jobs
crontab -e #to edit configuration for cron jobs

To enable cron job for magento 2, we firstly have to check where PHP CLI installed

which php 
#output can be
/usr/bin/php

and then, adding these lines into crontab

* * * * * /usr/bin/php /path to magento2/bin/magento cron:run | grep -v "Ran jobs by schedule" >> /path to magento2/var/log/magento.cron.log
* * * * * /usr/bin/php /path to magento2/update/cron.php >> /path to magento2/var/log/update.cron.log
* * * * * /usr/bin/php /path to magento2/bin/magento setup:cron:run >> /path to magento2/var/log/setup.cron.log

After that, you will not see this error message anymore

magento_cronjob_message

You can also run a cron in command line according to this syntax

magento cron:run [--group="cron_group_name"]

I hope this help you to quickly resolve your cron job setup for Magento 2.

PS: I have ran into permission issue with this cron job setting, it is because php script runs as current linux user, not as www-data user, so it created cache files without write permission to www-data users.

Warning: file_put_contents(/magento2/var/cache//mage-tags/mage---aa0_DB_PDO_MYSQL_DDL): failed to open stream: Permission denied in /magento2/vendor/colinmollenhour/cache-backend-file/File.php on line 663

I had to update cron setting to fix that issue like this

* * * * * www-data /usr/bin/php /path to magento2/bin/magento cron:run | grep -v "Ran jobs by schedule" >> /path to magento2/var/log/magento.cron.log
* * * * * www-data /usr/bin/php /path to magento2/update/cron.php >> /path to magento2/var/log/update.cron.log
* * * * * www-data /usr/bin/php /path to magento2/bin/magento setup:cron:run >> /path to magento2/var/log/setup.cron.log

I suppose that you are using apache as webserver.

Save

Save