Implementing cron for Magento 2

Using the enhanced cron.sh wrapper

Magento 2 does not come supplied with a cron.sh wrapper, and the default Magento cron documentation has some limitations, as it doesn't support email alerts or logging; and there are some edge cases that running the cron from the wider acc server may pose both a security risk - and the potential for path mismatch.

So the solution is to run a revised cron.sh wrapper that invokes the three key Magento 2 cron tasks as if it were on the web server itself.

Create a new file called cron.sh script with the following, filling in the email recipient if you also wish to be alerted of any cron execution errors.

Download and make the file executable by using,

cd /microcloud/domains/example/domains/example.com/http
wget --no-check-certificate -O cron.sh https://raw.githubusercontent.com/sonassi/magestack-scripts/master/cli/magento-2/cron.sh
chmod +x cron.sh

Setting up the crontab

Setting up your Magento cron is a simple task that requires a single edit to the www-data crontab,

crontab -e

* * * * * /usr/bin/timeout 6h /bin/bash /microcloud/domains/example/domains/example.com/http/cron.sh > /dev/null 2>&1

Examples

The following will run a custom composer command mymodule:mytask (although, you can obviously adjust it to suit),

0 5   * * * ( echo "cd /domains/example.com/http; php bin/magento mymodule:mytask" ) | /usr/bin/fakechroot /usr/sbin/chroot /microcloud/domains/example /bin/bash