Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

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.

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