Laravel 10 Cron Job Task Scheduling Tutorial with Example - TechvBlogs

Laravel 10 Cron Job Task Scheduling Tutorial with Example

Laravel 10 Cron Job Task Scheduling Tutorial with Example


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

10 months ago

TechvBlogs - Google News

What is Cronjob in Laravel?

In Laravel, a cron job is a scheduled task that runs automatically at specified intervals, similar to a system-level cron job.

Laravel's built-in task scheduler allows developers to define and schedule their own custom cron jobs within their Laravel applications. These cron jobs can be used for a variety of tasks, such as running background processes, sending emails, generating reports, and more.

The Laravel scheduler provides a simple and convenient way to define and manage these scheduled tasks, making it easy for developers to automate repetitive tasks and ensure that critical processes run on a regular basis.

Laravel 10 provides a robust and easy-to-use task scheduling system, which allows you to define recurring tasks and schedule them to run automatically at specified intervals. This system is built on top of the Unix cron daemon, and provides a simple and intuitive syntax for defining your scheduled tasks.

To get started, let's assume that you have a Laravel 10 application up and running on your server. To define a new scheduled task, you'll first need to create a new console command. You can do this by running the following Artisan command:

php artisan make:command MyScheduledTask

This will create a new file called MyScheduledTask.php in the app/Console/Commands directory. Open this file and you'll see a basic console command class that extends Laravel's Command class. This class should contain a handle() method, which is where you'll define the code that will be executed when your task runs.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyScheduledTask extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'my:scheduled-task';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        \Log::info("My Schedule Task");
        return 0;
    }
}

Now that we have a console command class, we can define a new scheduled task in our app/Console/Kernel.php file. Open this file and you'll see a $commands array, which contains a list of all the console commands that Laravel knows about. To add our new command to this list, we'll add the following line:

$schedule->command('my:scheduled-task')->daily();

This line tells Laravel to run our MyScheduledTask command once per day. You can customize the interval at which your task runs by calling any of the following methods on the $schedule object.

Task Schedule (Cronjob) Frequency Options

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
->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

For example, if you wanted to run your task every hour on the half-hour, you could use the following code:

$schedule->command('my:scheduled-task')->cron('30 * * * *');

Running Laravel Cron Jobs Locally Using the Scheduler's Run Command

Now that we've defined our scheduled task, we need to make sure that it actually runs on our server. To do this, we'll need to set up a cron job that calls Laravel's schedule:run command at regular intervals. This command will check to see if any scheduled tasks are due to run, and if so, it will execute them.

To run the Laravel scheduler locally, you can use the following command:

php artisan schedule:run

This command will check the schedule defined in the schedule() method of the App\Console\Kernel class, and will execute any tasks that are due to run at the current time.

By default, Laravel runs the scheduler every minute, so you can use this command in a separate terminal window to run the scheduled tasks in the background while you work on your project.

Note that running the schedule:run command locally is not the same as running it as a system-level cron job on a server. When running the scheduler locally, it is up to you to ensure that the command is run at the appropriate intervals to ensure that your tasks are executed as expected.

To set up the cron job, you'll need to add a new entry to your server's crontab file. This file tells the Unix cron daemon when to run each scheduled task. To open your crontab file for editing, run the following command:

crontab -e

This will open your crontab file in your default text editor. Add the following line to the file to run Laravel's schedule:run command every minute:

* * * * * php /path/to/your/laravel/app artisan schedule:run >> /dev/null 2>&1

Make sure to replace /path/to/your/laravel/app it with the actual path to your Laravel application.

And that's it! You've now set up a scheduled task that will run automatically on your server according to the schedule.

Conclusion

In conclusion, the Laravel 10 task scheduler is a powerful feature that allows developers to automate tasks within their Laravel applications. By defining scheduled tasks using the schedule() method in the App\Console\Kernel class, developers can specify exactly when and how often a given task should run.

In this tutorial, we've demonstrated how to create a new console command, define a new scheduled task, and run the Laravel scheduler locally using the schedule:run command. We've also shown how to use common scheduling options like daily(), hourly(), and everyMinute(), and how to use the cron() method to define custom scheduling intervals.

With the Laravel scheduler, developers can easily automate routine tasks, freeing up valuable time and resources to focus on other aspects of their application. We hope this tutorial has provided a useful introduction to the Laravel task scheduler and demonstrated some of the ways it can be used to improve your Laravel applications.

Comments (1)

Walter Wojcik Walter Wojcik 3 months ago

thank you !

Comment


Note: All Input Fields are required.