Laravel 11 Cron Job Task Scheduling Example

Hello developer, we'll learn about laravel 11 cron job task scheduling. Laravel's command scheduler offers a fresh approach to managing scheduled tasks on your server. Task scheduling is typically defined in your application's routes/console.php file.

In this article, we'll see how to create a cron job scheduler in laravel 11 and also see how to create a command in laravel 11. You set a cron job for minutes, hourly, daily, weekly, etc. as per your requirements.

Sometimes, we need to send reports via email, send PDF files, or take database backups using cron jobs in Laravel 11 as a developer

Cron Job Task Scheduling in Laravel 11

Laravel 11 Cron Job Task Scheduling

 

Step 1: Install Laravel 11

To install Laravel 11, execute the following command.

composer create-project laravel/laravel example-app

 

Step 2: Create a Command

To create a new custom command that will be executed with task scheduling using a cron job, run the following command.

php artisan make:command TestCron --command=test:cron

app/Console/Commands/TestCron.php

<?php
  
namespace App\Console\Commands;
  
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\User;
  
class TestCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test: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')
                    ]);
                }
            }
        }
    }
}

 

 

Step 3: Register Task Scheduler

In this step, we'll define our commands in the console.php file along with the scheduled time for running each command. We'll use functions like ->daily(), ->hourly(), etc.

routes/console.php

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

Frequencies that you can assign to a task:

Method Description
->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 = 0); Run the task every odd hour
->everyTwoHours($minutes = 0); Run the task every two hours
->everyThreeHours($minutes = 0); Run the task every three hours
->everyFourHours($minutes = 0); Run the task every four hours
->everySixHours($minutes = 0); 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
->quarterlyOn(4, '14:00'); Run the task every quarter on the 4th 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

 

Step 4: Run Scheduler Command

Now, we'll run the custom create command using the following laravel artisan command.

php artisan schedule:run

After running, the above command you will see an output like this.

storage/logs/laravel.php

[2024-04-10 23:45:03] local.INFO: Cron Job running at 2024-04-10 23:45:03
[2024-04-10 23:50:05] local.INFO: Cron Job running at 2024-04-10 23:50:05
[2024-04-10 23:55:04] local.INFO: Cron Job running at 2024-04-10 23:45:04

To view an overview of your scheduled tasks, use the schedule:list Artisan command. 

php artisan schedule:list

 

Laravel 11 Cron Job Setup on Server

In this step, we'll set up a cron job command on the server. If you're using Ubuntu Server, crontab is likely already installed. Run the command below to add a new entry for the cron job.

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

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS