How cron and Task Scheduler work in Laravel

Quite often I see people searching for "cron" in the Laravel context. The framework has a mechanism on top of Linux crontab to make it work. Let me show you how it works.

It is actually all described in the official docs here but that page is pretty long, and I want to shorten it to the essential things you need to know. Still, you may want to read the full docs, later.


Fundamentals: Cron Jobs

Now, how people used to run periodic automated jobs? With so-called cron jobs set up on the server. To set up a job to run every hour, for example, you would edit the crontab text file and add a line:

10 * * * * sh /path/to/script.sh

Those asterisks mean different periods:

  • minutes
  • hours
  • days of the month
  • months
  • days of the week

So, in the case above, the server should execute a script.sh at all hours at the 0 minute, which will be 9:00, 10:00, 11:00, etc. Once every hour.

So, you add more jobs like this, with different syntaxes for different periods.

In fact, you can use the crontab file to execute Laravel artisan commands, too. Like this:

10 9 * * * sh /path/to/your/project/php artisan some:command

That will execute php artisan some:command every day at 9:00.

But it's not convenient to connect to the server and set it all up manually on all servers, right? That's where the Laravel Task Scheduler function comes into play.


Laravel Task Scheduler

Laravel allows you to list all your commands in a specific file app/Console/Kernel.php, and you need to add only one cron command on your server:

1* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

This means that every minute the php artisan schedule:run will be executed and check if there are any commands to be run.

Here's the default main method of app/Console/Kernel.php:

1class Kernel extends ConsoleKernel
2{
3 protected function schedule(Schedule $schedule)
4 {
5 // $schedule->command('inspire')->hourly();
6 }
7 
8 // ...
9}

So this is the example syntax to put the commands into the schedule:

1$schedule->[command]()->[when_to_execute]();

You just need to list your commands here one by one, and the cron job running every minute will execute them.

There are a lot of different human-friendly syntax options for "when to execute". A few examples:

  • ->everyTwoMinutes()
  • ->hourly()
  • ->dailyAt('13:00')
  • ->weeklyOn(1, '8:00')
  • etc.

You can check them all in this section of the docs.

Also, there are different commands you can run here:

  • Artisan commands: $schedule->command('emails:send Taylor --force')
  • Jobs: $schedule->job(new Heartbeat)
  • Shell commands: $schedule->exec('node /home/forge/script.js')

And these are the basics that you need to know and understand Task Scheduling in Laravel. For all the details and other options, read the official docs.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by