Loading image

Blogs / Programming

Laravel 11 Cron Job Task Scheduling with Example

Laravel 11 Cron Job Task Scheduling with Example

  • showkat ali
  • 0 Comments
  • 33 View

Hello, everybody. We will learn about cron job task scheduling in Laravel 11. Laravel's command scheduler provides a new way to manage scheduled tasks on your server.

Task scheduling is typically defined in your application's ⁣ file.routes/console.php

In this article, we will learn how to create a cron job scheduler and a command in Laravel 11. You create a cron job for minutes, hours, days, weeks, and so on, depending on your requirements.

In Laravel 11, developers can use cron jobs to send reports, PDF files, and backup databases.

 

 

 

Cron Job Task Scheduling in Laravel 11

 

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')
                    ]);
                }
            }
        }
    }
}

 

Read Also: Laravel 11 Send Email with Attachment Example

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();

 

 We must specify our commands in the console.php file along with the desired execution time, as indicated by the functions below:

 

 

->everyMinute(); Run the task every minute
->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
->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 week
->weeklyOn(1, ‘8:00’); Run the task every week on Tuesday at 8:00
->monthly(); Run the task every month
->monthlyOn(4, ’15:00′); Run the task every month on the 4th at 15:00
->quarterly(); Run the task every quarter
->yearly(); Run the task every year
->timezone(‘America/New_York’); Set the timezone

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

 

Conclusion

Task scheduling in Laravel 11 is a simple and elegant way to automate your repetitive tasks. Whether it’s sending reminder emails, cleaning up logs, or backing up databases, Laravel provides a flexible and easy-to-use way to manage cron jobs. With minimal setup, you can schedule tasks to run at specific intervals and automate many aspects of your application, improving both efficiency and reliability..

 

  • Programming
showkat ali Author

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur based in Pakistan. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance

0 Comments

Post Comment

Recent Blogs

Recent posts form our Blog

Types of Sentence

Types of Sentence

Nasir Hussain
/
English

Read More
How to Use Summernote in React.js: A Simple Guide

How to Use Summernote in React.js: A Simple Guide

showkat ali
/
Programming

Read More
The Ultimate Guide to Data Structures: Understanding, Applications, and Best Practices

The Ultimate Guide to Data Structures: Understanding, Applications, and Best Practices

showkat ali
/
Programming

Read More
The Rise of AI: How Artificial Intelligence is Transforming Industries.

The Rise of AI: How Artificial Intelligence is Transforming Industries.

Sibgha jamil
/
Technology

Read More
9 Best Free Tools to Test and Improve Website Speed | Optimize Your Site in 2024

9 Best Free Tools to Test and Improve Website Speed | Optimize Your Site in 2024

showkat ali
/
Technology

Read More
5 Useful Examples from groupBy to Improve Your Laravel Skills

5 Useful Examples from groupBy to Improve Your Laravel Skills

showkat ali
/

Read More