Laravel Cron Job Task Scheduling Tutorial

To set up cron job task scheduling in Laravel follow the below steps.

  1. Create an artisan command to perform the particular action.
  2. Schedule the task in kernel.php
  3. Add Laravel task scheduler into crontab on the server.

Before diving deep into the above steps in this tutorial, let us explain what is cron jobs.

Cron jobs are scheduled tasks that run automatically on a server at specific intervals of time. This is mainly used to run scripts or commands on the server to perform some system maintenance, automated backups, log rotations, and other routine tasks. In the Laravel task scheduler, you can define tasks to be run at specific intervals, such as every minute, hourly, daily, weekly, or monthly. Once you have defined your tasks in the Laravel task scheduler, you can run the scheduler by configuring it in the crontab on the server.

In our example, we are creating a cron job task scheduling for a demo task.

Step 1: Create an artisan command

 In addition to the built-in artisan commands, Laravel allows us to create our own custom Artisan commands. These custom commands can be used to automate repetitive tasks in the project. So first we are going to create a custom artisan command for our particular action.

First, open the terminal and go to the project root directory. Then run the following command to create new custom artisan command.

php artisan make:command DemoDaily --command=demo:daily

Above command will create a DemoDaily.php file inside the app/Console/Commands folder.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class DemoDaily extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'demo:daily';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        \Log::info("DemoDaily is working!");      
    }
}

In the code protected $signature = 'demo:daily';, the word demo:daily will be used to run the artisan command. The function handle() is responsible for the functionality of the command or task. This function will be executed when the command or task is executed, and it receives any necessary input parameters as arguments. So we can implement our logic to perform any particular task inside this function. In our example, we have just logged a message “DemoDaily is working!”.

Next, register the newly created command in app/Console/Kernel.php file. In this file, protected $commands variable where you can register the command class as given below.

protected $commands = [
	Commands\DemoDaily::class,
];

Step 2: Schedule the task in kernel.php

Our next step is to schedule the task in app/Console/Kernel.php file. In our example, we are going to run the command demo:daily to perform a specific task on a daily bases.

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

The daily() method will run the command at midnight. However, you can customize the time at which the task should be run by passing an optional argument to the dailyAt() method. The ->dailyAt('13:00'); will run the task every day at 13:00.

We have many more task schedule frequencies that you can use for a task:

MethodDescription
->everyMinute();The task will run every minute.
->everyTwoMinutes();The task will run every two minutes.
->everyThreeMinutes();The task will run every three minutes.
->everyFourMinutes();The task will run every four minutes.
->everyFiveMinutes();The task will run every five minutes.
->everyTenMinutes();The task will run every ten minutes
->everyFifteenMinutes();The task will run every fifteen minutes.
->everyThirtyMinutes();The task will run every thirty minutes.
->hourly();The task will run every hour.
->hourlyAt(10);The task will run 10 minutes past the hour.
->everyOddHour();The task will run every odd hour
->everyTwoHours();The task will run every two hours.
->everyThreeHours();The task will run every three hours.
->everyFourHours();The task will run every four hours.
->everySixHours();The task will run every six hours.
->daily();The task will run every day at midnight.
->dailyAt('16:00'); The task will run every day at 16.00
->twiceDaily(4, 16);The task will run every day twice at 4.00 and 16.00
->twiceDailyAt(4, 16, 15);The task will run every day twice at 4.15 and 16.15
->weekly();The task will run every Sunday at 00:00
->weeklyOn(1, '10:00');The task will run every week on Monday at 10:00
->monthly(); The task will run on the first day of every month at 00:00
->monthlyOn(5, '16:00');The task will run on the 5th of every month at 16:00
->twiceMonthly(5, 20, '16:00');The task will run on the 5th and 20th of every month at 16:00
->lastDayOfMonth('15:00');The task will run on the last day of the month at 15:00
->quarterly();The task will run on the first day of every quarter at 00:00
->quarterlyOn(5, '20:00');The task will run every quarter on the 5th at 20:00
->yearly();The task will run on the first day of every year at 00:00
->yearlyOn(6, 1, '16:00');The task will run every year on June 1st at 16:00
->timezone('America/New_York');Set the timezone for the task.

Step 3: Add Laravel task scheduler into crontab on the server

You can run the task scheduler by the below command.

php artisan schedule:run

To run the Laravel scheduler on the server, one way is to add a single cron job entry to run the php artisan schedule:run command every minute. So, create a new crontab file, or edit an existing one by the below command.

crontab -e

Next, add the below lines in it.

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

For more detail read the Laravel doc.

Conclusion

Laravel's task scheduling allows you to easily run scheduled repetitive tasks automatically on a server. To set up cron job task scheduling in Laravel, the first step is to create a custom artisan command that performs a particular action. Then schedule the task to run the command on the schedule() method in  app/Console/Kernel.php file. Next, add php artisan schedule:run in crontab that runs every minute.