Get expert guidance in a few days with a Laravel code review

Tips for Using Laravel’s Scheduler

Published on by

Tips for Using Laravel’s Scheduler image

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.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article
Radiance: Generate Deterministic Mesh Gradient Avatars in PHP image

Radiance: Generate Deterministic Mesh Gradient Avatars in PHP

Read article
Speeding Up Laravel News With Cloudflare image

Speeding Up Laravel News With Cloudflare

Read article
Livewire 4 Support in Laravel VS Code Extension v1.4.3 image

Livewire 4 Support in Laravel VS Code Extension v1.4.3

Read article