Cron Job in Laravel 9 Using Laravel Scheduler

- LAST UPDATED

Cron jobs are one of the vital features that are needed for the proper working of an application. This is necessary for performing actions that may not be feasible to run when a client is interacting with the application. This tutorial is about setting up a cron job in Laravel 9 using the Laravel scheduler. Laravel's command scheduler is one of the best solutions to manage the scheduling of crons inside the application once the main cron is set up in the server. Earlier, we were forced to set cron jobs for each task in the cron server. This pain can easily be avoided by using Laravel scheduling.

Steps to Set up Cron Job in Laravel 9

If you are trying for the first time. Make sure that you already have a Laravel project installed. If not yet done, using composer, run the below command to create a new Laravel application with the name example-app

composer create-project laravel/laravel example-app

Once the application is ready, we need to navigate to the root of the application to run the command to create a console command which we will use to run using the Laravel scheduler.

Now run the artisan command to generate a new command for our application. CronTimer is the sample command that will be used as a sample command.

php artisan make:command CronTimer --command=cron:timer

The above code will create a console command named CronTimer in app\Console\Commands\CronTimer.php with code as shown below

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

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

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $array = [1,2,3,4,5];
        $bar = $this->output->createProgressBar(count($array));
        foreach ($array as $number) {
            echo $number;
            $bar->advance();
            sleep(1);
        }
        $bar->finish();
    }
}

 

Once a command is generated, we can test it by running it using the command's signature. For the above example, as shown below

php artisan cron:timer

And it will give an output like this in console.

Setting up Laravel scheduler

In this, we will set up a scheduler to run this command for a particular period of time. For this, we need to make a small change in the app\Console\Kernel.php

We are adding the command with its schedule to the scheduler. Just have a look at the updated code in kernel.php.

 

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('cron:timer')->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

So we scheduled to run our command every minute. 

Testing Scheduler in our local machine

We already checked the command on our local machine. Now let's test to find whether our cron is working correctly locally.

php artisan schedule:work

We can start seeing the commands one by one based on their schedule. Just have a look at the screenshot for the same.

To set up this in a ubuntu Linux machine we can make use of crontab.

After entering crontab we can add this command to start running schedules in Laravel.

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

There are so many options available to run commands using Laravel scheduler. Here it some of the methods and its use cases.

Method Description
->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
->everyOddHour(); Run the task every odd 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
->twiceDailyAt(1, 13, 15); Run the task daily at 1:15 & 13:15
->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
->twiceMonthly(1, 16, '13:00'); Run the task monthly on the 1st and 16th at 13:00
->lastDayOfMonth('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
->yearlyOn(6, 1, '17:00'); Run the task every year on June 1st at 17:00
->timezone('America/New_York'); Set the timezone for the task

For more reference visit Laravel documentation for scheduling