Laravel 11 Cron Job Task Scheduling Tutorial

Reading Time: 7 minutes
26 Views

Efficient task automation is a cornerstone of modern web applications, and Laravel 11 makes it easier than ever with its robust task scheduling system. Gone are the days of manually configuring cron jobs for individual tasks.

With Laravel’s elegant syntax and powerful schedule method, you can manage repetitive actions like sending emails, cleaning up databases, or generating reports, all within your application code. In this tutorial, we’ll walk you through setting up cron job task scheduling in Laravel 11.

Read More: Laravel 11 RESTful APIs with JWT Authentication Tutorial

Let’s get started.

Laravel Installation

To create a laravel project, run this command into project terminal

composer create-project laravel/laravel demo-app

Create New Laravel Command

Next, we’ll create a custom command that will run with task scheduling using a cron job. Use the following command to generate a new custom command:

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

It will create a file DemoCron.php inside app/Console/Commands folder.

Open command file and write this code into it,

<?php
  
namespace App\Console\Commands;
  
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\User;
  
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.
     */
    public function handle()
    {
        info("Cron Job running at ". now());
      
        $response = Http::get('https://jsonplaceholder.typicode.com/users');
          
        $users = $response->json();
      
        if (!empty($users)) {
            foreach ($users as $key => $user) {
                if(!User::where('email', $user['email'])->exists() ){
                    User::create([
                        'name' => $user['name'],
                        'email' => $user['email'],
                        'password' => bcrypt('123456789')
                    ]);
                }
            }
        }
    }
}

Register as Task Scheduler

Now, we’ll define our commands in the console.php file, specifying the schedule for when each command should run, as shown in the following example:

MethodDescription
->cron('* * * * *');Run the task on a custom cron schedule.
->everySecond();Run the task every second.
->everyTwoSeconds();Run the task every two seconds.
->everyFiveSeconds();Run the task every five seconds.
->everyTenSeconds();Run the task every ten seconds.
->everyFifteenSeconds();Run the task every fifteen seconds.
->everyTwentySeconds();Run the task every twenty seconds.
->everyThirtySeconds();Run the task every thirty seconds.
->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($minutes);Run the task every odd hour.
->everyTwoHours($minutes);Run the task every two hours.
->everyThreeHours($minutes);Run the task every three hours.
->everyFourHours($minutes);Run the task every four hours.
->everySixHours($minutes);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 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 on the 1st and 16th of every month 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.
->quarterlyOn(4, '14:00');Run the task on the 4th day of every quarter at 14: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.

Add Console Route

Open console.php file from routes folder,

<?php
  
use Illuminate\Support\Facades\Schedule;
  
Schedule::command('demo:cron')->everyMinute();

Read More: Laravel 11 RESTful APIs with Sanctum Authentication

Run Scheduler Command For Test

Now we’re ready to run our cron job.

You can manually check its execution using the following command:

php artisan schedule:run

After running the above command, you can check the log file where we’ve printed some text for verification.

Open your log file to see the output, which should look similar to the following:

[2025-01-05 03:51:02] local.INFO: Cron Job running at 2024-01-05 03:51:02  
[2024-01-05 03:52:01] local.INFO: Cron Job running at 2024-01-05 03:52:01  
[2024-01-05 03:53:02] local.INFO: Cron Job running at 2024-01-05 03:53:02  

Laravel 11 Cron Job Setup on Server

Here’s how to set up a cron job command on your server.

If you’re using an Ubuntu server, crontab is usually pre-installed. Run the following command to add a new entry for your cron job:

crontab -e

Now, add the following line to your crontab file. Ensure you replace <path-to-your-project> with the correct path to your project:


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

That’s it.

We hope this article helped you to learn about Laravel 11 Cron Job Task Scheduling Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.