User Defined Schedules in Laravel

Published on by

User Defined Schedules in Laravel image

Recently Adam Wathan and Taylor Otwell have used Basecamp to track what they are doing every day–a tech diary. Notably, they are using the check-in feature which allows you to schedule questions to be sent to members about almost anything. Taylor and Adam are using it for “What did you work on today?” This is great because:

  • A) Taylor is a tease!
  • B) I noticed there was a schedule set for every weekday at 4 pm.

It’s not that it’s the same time of day or even that it’s only weekdays which peaked my curiosity but the fact every check-in has a custom schedule defined by a user.

In Laravel, we can quickly schedule a job to run every weekday at 4 pm, and we can use a custom timezone.

$schedule->job(SendCheckinNotification::class)
->weekdays()
->at('16:00')
->timezone('MST');

But out of the box, we cannot set a different schedule for every individual check-in. We would have to store a cron expression and manually check every minute if it’s due.

Source Code Diving

As Jeffrey Way will attest, “you should look at the source code.” I found there is already a trait, ManagesFrequencies, which allows you to set the schedule for any model or class; a major bonus. But this is not the whole picture.

Diving deeper into how the schedule works I realized you need a cron expression, a timezone, and a means to test if an expression is valid. All of this was in the Scheduling\Event class which I used as the basis for a Schedulable trait.

Show Me the Code!

Here is a gist for the Schedulable Trait.

This trait, when used by a model or class, allows you to define it’s schedule (cron expression) quickly but also makes it super easy to implement in the kernel’s schedule.

protected function schedule(Schedule $schedule)
{
$schedule->call(function(){
Checkin::all()->filter->isDue->each->sendNotification();
})->everyMinute();
}

In this code, I used higher-order functions to filter down to only those objects that are due (their schedule says “Do it now!”) and then on each of these, call a method that sends a notification.

This Trait is only useful when a model/class allows for a variable schedule. If the schedule is fixed, then you can use Laravel’s existing implementation.

To use this with a model, you would need to add an expression and timezone field to your model and save it after changing the schedule.

$this->weekdays()->at('16:00')->save();
 
//Or you could pass in a expression string
$this->update([
'expression' => '15 * * * 1,2'
]);

(Every 15th minute past every hour on Monday and Tuesday.)

If you want to use this with a Laravel model you can add a static method which wraps it up further.

public static function areDue()
{
return self:all()->filter->isDue();
}

And to call it in the scheduler:

$schedule->call(function(){
Checkin::areDue->each->sendNotification();
})->everyMinute();

So if you ever need to have a model or class do something on a bespoke schedule like sending out notifications, billing processing, or just applying a custom timezone on the object rather than stored on a user or team, the Schedulable Trait will help you out!

Next Step

Since starting this, I have submitted a PR to the Laravel Framework in hopes of finally adding to the codebase. Putting this into core is the sleekest, most simple means of making it available with just one Trait, one additional method in schedule and a new event class behind the scenes. You could add a schedulable class like this:

$schedule->use(Checkin::class);

The flip side, however, is it will rarely be used, and it is a focused implementation rather than a larger shift in how the schedule works. Alas, it won’t be implemented in core just yet.

Package-ify It!

To release this as a package is the next step as developers can bring it in when they need it, but there is one big drawback. Schedule is not macroable, and so there would need to be an ugly workaround to inject an event into the schedule from a service provider rather than from kernel.php.

Wrap Up

Not only was I able to build something that improves my code, I learned how Laravel’s scheduler works internally and how there are hidden gems in the source code waiting to be used in ways they were not intended!

David Piesse photo

Developer Dad on the side

My day job is using Laravel and GIS to find bombs, people and heroin in Afghanistan. Alas it's not super glamorous but it's a +1 doing good.

I love to code - from age 13 when I built a text based MMORPG in PHP. Since finding Laravel I have embraced it, built dozens of things, from a crappy SpaceX kids game for my son, to hack winning ideas such as Earthquake Stream and running Laravel Advent where I interviewed a top Laravel personality for every day in the lead up to Xmas 2017.

Always happy to talk with anyone about what they are doing and I love hearing what people do with code and in regular life.

Cube

Laravel Newsletter

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

image
Laravel Forge

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

Visit Laravel Forge
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
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

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
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

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

Rector

The latest

View all →
Launch your Startup Fast with LaraFast image

Launch your Startup Fast with LaraFast

Read article
Embed Livewire Components on Any Website image

Embed Livewire Components on Any Website

Read article
Statamic announces next Flat Camp retreat (EU edition) image

Statamic announces next Flat Camp retreat (EU edition)

Read article
Laravel Herd releases v1.5.0 with new services. No more Docker, DBNGIN, or even homebrew! image

Laravel Herd releases v1.5.0 with new services. No more Docker, DBNGIN, or even homebrew!

Read article
Resources for Getting Up To Speed with Laravel 11 image

Resources for Getting Up To Speed with Laravel 11

Read article
Laravel 11 streamlined configuration files image

Laravel 11 streamlined configuration files

Read article