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.

Laravel Forge logo

Laravel Forge

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

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
Bacancy logo

Bacancy

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

Bacancy
Lucky Media logo

Lucky Media

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

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article