Code review at scale is broken. Here’s how Augment Code is fixing it.

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
Jump24 - UK Laravel Agency

Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Visit Jump24 - UK Laravel Agency
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
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
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 →
"The Vibes" — NativePHP Hosts a Day 3 after Laracon US image

"The Vibes" — NativePHP Hosts a Day 3 after Laracon US

Read article
What We Know About Laravel 13 image

What We Know About Laravel 13

Read article
New Colors Added in Tailwind CSS v4.2 image

New Colors Added in Tailwind CSS v4.2

Read article
Factory makeMany() Method in Laravel 12.52.0 image

Factory makeMany() Method in Laravel 12.52.0

Read article
Laravel Adds an Official Svelte + Inertia Starter Kit image

Laravel Adds an Official Svelte + Inertia Starter Kit

Read article
MongoDB Vector Search in Laravel: Finding the Unqueryable image

MongoDB Vector Search in Laravel: Finding the Unqueryable

Read article