Digging Deeper
Task Scheduling
Introduction
Laravel's scheduler lets you define your schedule in code, then needs one cron entry on your server. That cron entry was always a line of shell, so it works as it is:
* * * * * cd /var/www/html && ./artisan schedule:run >> /dev/null 2>&1
Defining Schedules
Schedules are defined in routes/console.sh:
schedule inspire everyMinute
schedule queue:retry hourly
| Frequency | Runs |
|---|---|
everyMinute | Every minute |
everyFiveMinutes | When the minute is divisible by 5 |
hourly | At minute 0 |
daily | At midnight |
./sail artisan schedule:list
Running the Scheduler Locally
Without cron, schedule:work runs the schedule every minute. ./artisan dev starts it for you.
./sail artisan schedule:work
It sleeps until the start of the next minute, rather than for 60 seconds, which would drift by however long the tasks took:
sleep $(( 60 - $(printf '%(%s)T' -1) % 60 ))
note
The minute is read with printf '%(%M)T', which gives 08 at eight minutes past. Bash reads numbers with a leading zero as octal, and 08 is not a valid octal number, so the scheduler breaks at 8 and 9 minutes past every hour. $((10#$minute)) forces base 10.
Preventing Task Overlaps
Every scheduled command runs under flock -n, which is withoutOverlapping():
flock -n "storage/framework/schedule-inspire.lock" ./artisan inspire
flock takes a lock on the file for as long as the command runs. -n means don't wait: if a previous run still holds the lock, give up and skip this one. The kernel releases the lock when the process exits, even if it crashes, so there are no stale lock files to clean up.
Output
Each scheduled command's output is broadcast on the artisan channel, so it appears on the Artisan example every minute.