Laravel 8/9 Cron Job Task Scheduling Tutorial with examples

Laravel 8/9 cron job task scheduling; In this tutorial you will learn how to set up cron job task in a Laravel 8/9 application.

What is a Cron?

Cron is a command to an operating system or server for a scheduled job that is to be executed at a specified time. The process of running a cron is called Cron Job. A cronjob consists of two required configurations, a command to run and the time.

Why Laravel 8/9 Cron Scheduler?

Since a cronjob is set directly on the server, most of the times it is quite painful because your task scheduler is not inside your code. Hence, you have to SSH into your server to view your existing cron job entries or add additional entries.

This is where Laravel’s inbuilt command scheduler comes to help. It offers a fresh approach to managing scheduled tasks on your server. With it you can define all cronjobs or command schedules directly within your Laravel Application. Then, only one cron entry will be required on your server to call Laravel’s cron scheduler.

Step 1: Install Laravel 9

In this step, if you haven’t setup laravel 8/9 application yet then setup a fresh laravel 9 application. For this let’s run the command as shown below to get clean fresh Laravel 9 application.

composer create-project --prefer-dist laravel/laravel laravelcron

Command Vs. Closures

In order to understand this let us take a look at the App\Console\Kernel.php file’s schedule method. Your app is already set to receive commands, as we can see the use of Schedule console at the top of Kernel.php file, i.e.

use Illuminate\Console\Scheduling\Schedule;

So if we look at schedule method we can see a commented out line of code which reads:

//$schedule->command('inspire')->hourly();

Uncomment the line above and system will run inspire command every hours! After uncommenting run:

php artisan schedule:list

which will show:

0 * * * * php artisan inspire ............................................................................................ Next Due: 50 minutes from now

(Note: minutes may vary for your console)

(Closures are another way to define scheduled jobs inside the schedule method which we will discuss down the page.)

Once you see the result above, you can comment that line out again so that we can play with with our own custom commands.

Step 2: Create New Command

In this step, we will create a new custom command for test purpose. This custom command will execute with task scheduling cron job. Let’s create new custom command.

php artisan make:command DemoCron –-command=demo:cron

This will create a new DemoCron.php in App/Console/Commands folder with some default code and with a handle() function.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

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

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        \Log::info("DemoCron command is running!");
        //Write your logic here, for example
        //DB::table('recent_users')->delete();
        return Command::SUCCESS;
    }
}

Now update the App/Console/Kernel.php‘s schedule method to include demo:cron command to be run everyMinute.

protected function schedule(Schedule $schedule)
{
    // $schedule->command('inspire')->hourly();
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('demo:cron')->everyMinute();
    }
}

Following are the different Schedule Frequency options list that allows you to schedule your tasks with different rate of occurrences.

MethodDescription
->cron(‘* * * * *’);Run the task on a custom Cron schedule
->everyMinute();Run the task every minute
->everyTwoMinutes();Run the task every two minutes
->everyThreeMinutes();Run the task every three minutes
->everyFourMinutes();Run the task every four minutes
->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
->everyTwoHours();Run the task every two hours
->everyThreeHours();Run the task every three hours
->everyFourHours();Run the task every four hours
->everySixHours();Run the task every six hours
->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
->monthlyOnLastDay(’15:00′);Run the task on the last day of the month 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

Hint: You can give precedence to Laravel Scheduling Tasks by examining the Laravel Documentation.

Running The Scheduler

Now that we have learned how to create define scheduled task commands, let’s discuss how to actually run them on our server. The php artisan schedule:run Artisan command will run all of your scheduled tasks immediately.

So, when using Laravel’s scheduler, you only need to add a single cron entry to your server that runs the schedule:run command every minute. i.e.

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

Running The Scheduler Locally

Typically, you would not add a scheduler cron entry to your local development machine. Instead, you may use the schedule:work Artisan command.

php artisan schedule:work

This command will run in the foreground and invoke the scheduler every minute until you terminate the command.

When you run the scheduler it will print something like the following lines to laravel.log file

[2022-10-11 09:49:48] local.INFO: DemoCron command is running!
[2022-10-11 09:50:14] local.INFO: DemoCron command is running!
[2022-10-11 09:50:19] local.INFO: DemoCron command is running!
[2022-10-11 09:50:24] local.INFO: DemoCron command is running!
[2022-10-11 09:51:00] local.INFO: DemoCron command is running!

Using Closures

You may define all of your scheduled tasks directly in the schedule method of your application’s App\Console\Kernel class using closures. For example

protected function schedule(Schedule $schedule)
{
    // $schedule->command('inspire')->hourly();
    $schedule->call(function () {
        DB::table('recent_users')->delete();
    })->daily();
}

I hope you find it useful!

Leave a Reply