The execution of scheduled tasks in Laravel is implemented through cron. The official website document is a simple one-line Cron code
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
But in the actual use process, if you are not familiar with Linux and Cron, you will encounter some We have compiled and recorded the small pits and shared them in the hope that they can help everyone.
Pit 1: Environment variables
When Cron fails to take effect, it may be caused by incorrect Cron execution environment variables.
Execute the command
env > /tmp/env.output
Open the /tmp/env.output file and add the entire line of the PATH field to the top of the corntab file. The corntab file is in the /var/spool/cron directory
crontab file example
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/opt/mysql/bin:/opt/php7/bin:/opt/memcached/bin:/root/bin * * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
Pit 2: Cron execution user causes Laravel log to be unwritable
The Cron created through the crontab -e command belongs to the root user. If it is scheduled If the task actively writes logs during execution or encounters exceptions that are not caught, a log file with root permissions will be created, which will eventually cause the www account of php-fpm to be unable to write.
Therefore, you need to specify the user when creating cron
crontab -u www -e
In the personal management system, the php-fpm execution user is www. Please adjust the code according to your actual situation.
Pit 3: The last line of cron content does not have a carriage return
After solving the above two problems, if you still find that cron does not execute, please confirm
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
The code has a carriage return and line feed at the end.
This trap bothered the engineer all afternoon...
The above is the detailed content of Laravel Cron scheduled task 'jumping pit' point. For more information, please follow other related articles on the PHP Chinese website!