Tips for Using Laravel’s Scheduler

Tips for Using Laravel’s Scheduler

Laravel’s task scheduling features are well documented and give you the full power of cron in a fluent API. The documentation covers most of what you need to get up and running with the scheduler quickly, however, there are a few underlying concepts I’d like to cover related to cron that will help solidify your understanding of how Laravel determines which scheduled tasks should run.

Understanding Cron

At the foundation of Laravel’s scheduler, you need to understand how to schedule tasks on a server through Cron’s somewhat confusing syntax.

Before we dive into understanding cron better and resources you can use to familiarize yourself with cron, let’s look at the essential pieces of the scheduler.

First, you define scheduled tasks through your Laravel application’s App\Console\Kernel::schedule() method:

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    // $schedule->command('inspire')
    //         ->hourly();
}

You can use this method to define all of the scheduled tasks that need to run. The Schedule instance method command() returns an instance of the Illuminate\Console\Scheduling\Event class.

If you want to tinker/debug with an instance of the event class, you can dump like the following example:

$event = $schedule->command('inspire')
                  ->hourly();

dd($event->expression); // "0 * * * *"

To trigger this method, run artisan:

> php artisan
"0 * * * *"

The event instance has an expression property that stores the cron representation of the task after the fluent API calls.

Keep this example’s value in mind while we talk about cron.

Laravel shields you from cron with the scheduler’s fluent API—in our example the hourly() method—but understanding cron will help you understand better how to troubleshoot what is going on under the hood.

Here’s a text representation that should clarify how cron works if you’re not familiar (even if you are I bet this is still useful):

# Use the hash sign to prefix a comment
# +---------------- minute (0 - 59)
# |  +------------- hour (0 - 23)
# |  |  +---------- day of month (1 - 31)
# |  |  |  +------- month (1 - 12)
# |  |  |  |  +---- day of week (0 - 7) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *  command to be executed
#-----------------------------------------------------------

Using the above example of “0 * * * *” this task will run at the zero minute mark every single hour of every day of every month on every day of the week.

Cron also has some other formats that might feel weird, such as the expression generated using Laravel’s quarterly() method:

0 0 1 1-12/3 *

Running a task quarterly means it will run at 00:00 on the first day of the month in every third month from January to December. The weird 1-12/3 syntax is called a “step value” which can be used in conjunction with ranges. The crontab – Linux manual page describes step values as follows:

Step values can be used in conjunction with ranges. Following a range with “” specifies skips of the number’s value through the range. For example, “0-23/2” can be used in the hours’ field to specify command execution every other hour (the alternative in the V7 standard is “0,2,4,6,8,10,12,14,16,18,20,22”). Steps are also permitted after an asterisk, so if you want to say “every two hours”, just use “*/2”.

I’d encourage you to read through the man-page, or at least keep it handy if you run into a situation where you need to understand the underlying cron schedule for a task better.

Understanding the Scheduling Event API

Laravel has some excellent fluent APIs that allow you to chain multiple method calls together. The scheduling Event class is no different. However, there are some nuances with some of the combinations you might use.

Take the following as an example to better illustrate: let’s say that we want a command to run hourly, but only on Monday, Wednesday, and Friday:

$schedule->command('inspire')
         ->hourly()
         ->mondays()
         ->wednesdays()
         ->fridays();

You might think the above command achieves the correct cron, but that’s not how it works. In the above example, the last “day” method called is fridays(), thus, here’s what the cron looks like:

0 * * * 5

The above task will run hourly, but only on Friday.

Before I show you the correct method call to achieve what we want, let’s look at the Event::fridays() method. The fridays() method (and many others) come from Laravel’s ManagesFrequencies trait:

/**
 * Schedule the event to run only on Fridays.
 *
 * @return $this
 */
public function fridays()
{
    return $this->days(5);
}

The method calls another method on the same trait days() which looks like the following at the time of writing:

/**
 * Set the days of the week the command should run on.
 *
 * @param  array|mixed  $days
 * @return $this
 */
public function days($days)
{
    $days = is_array($days) ? $days : func_get_args();

    return $this->spliceIntoPosition(5, implode(',', $days));
}

You can look at the details of how spliceIntoPosition() works, but all of the “day” methods overwrite each other, so the last one called sticks.

Here’s how you’d write the correct schedule using Laravel’s fluent API:

$schedule->command('inspire')
         ->hourly()
         ->days([1, 3, 5]);

Debugging this Task instance yields the following expression:

0 * * * 1,3,5

Bingo!

Using Cron Directly

Most of the time I think most people prefer to use Laravel’s fluent API. However, the Event task includes a cron() method to set the expression directly:

$schedule->command('inspire')
         ->cron('0 * * * 1,3,5');

I’d argue that Laravel’s fluent API is a more readable way to define the command, but you can get the full power of cron directly with this method if you’d rather use cron syntax.

Crontab Guru

For advanced use-cases and better understanding how your scheduled tasks are going to run, consider debugging the underlying cron expression and using a tool like crontab.guru – the cron schedule expression editor.


Filed in: Laravel Tutorials / Cron / Scheduler


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

PHP Web Developer
Orlando, FL
Christ for all Nations
PHP Developer
Manhattan, KS (open to Remote)
CivicPlus
Mid-Senior Laravel Developer
Exeter
Optix Solutions
Full Stack Web Developer
Las Vegas, NV
V Shred
Staff Software Engineer (Laravel)
Remote
smartbnb
Software Engineer (PHP, Laravel, Vue)
Los Angeles, CA
Relocity
Software Engineer Level 1 / Level 2
St. Pete. / Tampa Area, FL / Remote
ShineOn