We have a lot of tasks run to a bewildering schedule across multiple servers. We use cron, of course. But maintaining the schedule is painful. Very painful.

We’ve tried committing copies of the crontab to a repository, but they’re almost never up-to-date.

And worse, if I need to do something even moderately complex like, say, schedule a job to run every two weeks, cron starts to get complicated.

But things just got better.

Laravel 5 allows us to easily manage our scheduling from within our application. Let’s take a look at the bi-weekly scheduling referred to in this post’s title.

Sure, we could do this with cron. It would something like this:


0 1 * * Sat expr `date +\%s` / 604800 \% 2 >/dev/null || /path/to/script.sh

Source: Stackoverflow
This divides the number of seconds since the Linux epoch by the number in a week to determine whether it’s an odd or an even week. But it’s ugly and needs close reading to figure out.

The Laravel version is easier to understand, and a whole heap more elegant:


$schedule->command('foo')->weeklyOn(5, '00:01')->when(function() {
    return (time() / 604800 % 2);
});

We can use Laravel’s fluent interface to set the time and day for execution and a closure to restrict it to alternate weeks and then commit the result into our git repository.

This is just one example of using Artisan scheduling. For more information, I recommend checking out the official Laravel documentation.