How to Schedule tasks with cron jobs using Laravel Scheduler

By Parth Patel on Apr 13, 2020

In big application, you often need to schedule periodic tasks using Cron jobs. But after some point, it becomes cumbersome to manage those cron jobs. Laravel Scheduler is a command line facility which allows you to easily manage and schedule tasks using cron jobs. There are various use-cases where you would need to schedule tasks like - scheduling backups, promotional emails, data fetching apis etc.

To setup Laravel Scheduler, you only need to setup single cron job in your server. Using that, Laravel scheduler will manager all your scheduled tasks fluently.

Let's first understand what do you mean by Cron jobs.

What is Cron

Cron is a task scheduler in Unix/Linux operating systems. It executes shell commands at pre-defined intervals in the format of cron expression. To manage these scheduled commands, cron uses a configuration file called crontab. These scheduled commands are known as cron jobs which are recorded in crontab or cron table. Below is the structure of the command you would write in the crontab file to schedule it:

* * * * * command/to/run

Here, "* * * * *" is the cron expression to determine the scheduled interval. Each * represents time format in the following order:

minute, hour, day of the month, month and day of the week ~ asterisk means all possible values

Example:

Cron expression to run command everyday at 9 AM in morning - 0 9 * * *

Setup Laravel Scheduler

Okay, so now you know the basics of cronjobs, let's setup the laravel scheduler in crontab. In your server's crontab, add the following entry:

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

This cron will execute "php artisan schedule:run" command every minute in the system and from there, laravel schedule does its magic!

How to schedule tasks

Now, we will learn how to schedule tasks in Laravel along with specified interval for Laravel Scheduler to execute.

To schedule tasks, you can define tasks in the schedule method of the App\Console\Kernel class. You can schedule tasks in various ways:

  • Passing a closure function to schedule object's call method
  • Using artisan command
  • Using Queued Jobs
  • Executing shell commands
  • You can call any invokable objects by passing it to call method

Schedule Closure/Callback Function

In laravel Scheduler, you can schedule closure or Callback functions easily using schedule object's call method. Let's look at an example where we will schedule a closure function which deletes any user who didn't login since 1 year.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            DB::table('users')->whereYear('last_login_at','<',date('Y')-1)->delete();
        })->daily();
    }
}

Schedule Artisan Command

You can also schedule artisan commands using Laravel Scheduler. Let's see an example below which will run artisan command every day at midnight to backup database (Note: Here I am using hypothetical artisan command for example purpose):

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('run:backup')->daily();
    }
}

In above example, you can see that we added entry to schedule artisan command to run backup operation daily at midnight. You can notice that we used ->daily() to set the frequency to daily at midnight. You can use various types of frequency commands which are listed below:

Laravel Schedule Frequency Options

Method

Description

->cron('* * * * *');

Run the task on a custom Cron schedule

->everyMinute();

Run the task every minute

->everyFiveMinutes();

Run the task every five minutes

->everyTenMinutes();

Run the task every ten minutes

->everyFifteenMinutes();

Run the task every fifteen minutes

->everyThirtyMinutes();

Run the task every thirty minutes

->hourly();

Run the task every hour

->hourlyAt(17);

Run the task every hour at 17 minutes past the hour

->daily();

Run the task every day at midnight

->dailyAt('13:00');

Run the task every day at 13:00

->twiceDaily(1, 13);

Run the task daily at 1:00 & 13:00

->weekly();

Run the task every sunday at 00:00

->weeklyOn(1, '8:00');

Run the task every week on Monday at 8:00

->monthly();

Run the task on the first day of every month at 00:00

->monthlyOn(4, '15:00');

Run the task every month on the 4th at 15:00

->quarterly();

Run the task on the first day of every quarter at 00:00

->yearly();

Run the task on the first day of every year at 00:00

->timezone('America/New_York');

Set the timezone

This is just the basics of task scheduling using Laravel Scheduler. Laravel Scheduler is a very advanced tool therefore you can utilize it for more complex operations.

I hope this article helped you to learn how to schedule tasks using Laravel Scheduler. Let me know how you are using Laravel scheduler in your application!

Adios