Laravel Task Scheduling

Laravel Task Scheduling

 

To manage scheduled tasks on the server, a fresh approach is offered by Laravel’s command scheduler. The scheduler permits you to boldly and uniformly outline your command scheduled in the Laravel application. Solely a single Cron entry is required, while using the scheduler, on your server. Task scheduler is outlined within the app/console/Kernel.php file’s ‘schedule’ method.

# Defining Scheduler:

In the App/Console/Kernal class, we define all scheduled tasks within the ‘schedule’ method.

<?php

      namespace App\Console;

      use Illuminate\Console\Scheduling\Schedule;

      use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

      use Illuminate\Support\Facades\DB;

      class Kernel extends ConsoleKernel

      {

           /**

           * The Artisan commands provided by your application.

           *

           * @var array

           */

           protected $commands = [

                 //

           ];

          /**

          * Define the application's command schedule.

          *

          * @param  \Illuminate\Console\Scheduling\Schedule  $schedule

          * @return void

          */

          protected function schedule(Schedule $schedule)

          {

              $schedule->call(function () {

                  DB::table('post')->delete();

              })->daily();

         }

      }

To read a summary of your scheduled tasks, use the schedule: list artisan command.

php artisan schedule: list

# Scheduling:

  • Artisan command:

You can also schedule Artisan and system commands, in addition to closures. To schedule an Artisan command, you can use the command method with either command’s name and class.

You can transfer an array of additional command-line arguments to Artisan Commands while scheduling them using the command’s class name.

use App\Console\Commands\SendNotificationCommand;

$schedule->command('emails:send John --force')->daily();

$schedule->command(SendNotificationCommand::class, ['John', '--force'])->daily();

 

Queued Jobs:

A queued work can be scheduled using the job method. This approach makes it simple to schedule queued jobs without having to use the call method to specify closures.

use App\Jobs\ApplyPost;

$schedule->job(new ApplyPost)

                   ->everyFiveMinutes();

 

#Frequency Options:

METHOD DESCRIPTION
->cron(‘* * * * *’); Run the task on a custom cron schedule
->everyMinute(); Run the task every minute
->everyTwoMinute(); Run the task every two minutes
->everyThreeMinute(); Run the task every three minutes
->everyFourMinute(); Run the task every four minutes
->everyFiveMinute(); Run the task every five minutes
->everyTenMinute(); Run the task every ten minutes
->everyFifteenMinute(); Run the task every fifteen minutes
->everyThirtyMinute(); 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
->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 every day at 1:00 & 13:00
->weekly(); Run the task every Sunday at00: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 4th at 15:00
->twiceMonthly(1, 16, ’17:00’); Run the task monthly on the 1st and 16th at 17: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(); Run the task every year on June 1st at 17:00
->timezone(‘America/New_York’); Set the time zone for the task

 

 

 

The following is a list of additional scheduling constraints.

METHOD DESCRIPTION
->weekdays(); Limit the task to weekdays
->weekends(); Limit the task to weekends
->sundays(); Limit the task to Sunday
->mondays(); Limit the task to Monday
->tuesdays(); Limit the task to Tuesday
->wednesdays(); Limit the task to Wednesday
->thursdays(); Limit the task to Thursday
->fridays(); Limit the task to Friday
->saturdays(); Limit the task to Saturday
->days(array|mixed); Limit the task to specific day
->between($startTime, $endTime); Limit the task to run between  start and end times
->unlessBetween($startTime, $endTime); Limit the task to not run between  start and end times
->when(Closure); Limit the task based on a truth test
->environments($env); Limit the task to specific environments

# To Prevent Task Overlaps:

Even if the previous instance of the task is still running, scheduled tasks are performed by default. And withoutOverlapping approach can be used to avoid this.

withoutOverlapping method is particularly useful if your task has a wide range of execution time, making it difficult to predict how long each task will take.

$schedule->command (‘emails:send’)

                                   ->withoutOverlapping();

 

# To Run Task on One Server:

Use the onOneServer method when specifying the scheduled task to show that the task can run only on one server. To prevent another server from running the same tasks at the same time the first server will save an atomic lock on the job.

$schedule->command(‘report:create’)

                                   ->Fridays()

                                   ->at(‘10:00’)

                                   ->onOneServer();

 

# For Background Task:

Multiple task schedules at the same time will run in the order specified in the scheduler method, by default. This will cause consequent tasks to start much longer than planned. Use the runInBackground method to execute tasks in the background at the same time.

$schedule->command(‘report:create’)

                                  ->daily()

                                  ->runInBackground();

 

# To Run Task on One Server:

Scheduled tasks will run when an application is in maintenance mode. 

If you want to compel a task to run even in maintenance mode, 

use evenInMaintenanceMode method while defining it.

$schedule->command(‘emails:send)

                                   ->daily()

                                   ->evenInMaintenanceMode();

 

#To Run the Scheduler:

To run scheduled tasks on server use schedule: run artisan command. Based on the current time on the server, this Artisan command will analyze all scheduled tasks and decide if they need to run.

php artisan schedule:run

 

#To Run the Scheduler locally:

On your local development machine instead of adding a scheduler cron entry, you can use the schedule: work artisan command. And it will run in the foreground, invoking the scheduler every minute, until you terminate it.

php artisan schedule:work

 

#Task Outputs:

A number of useful methods are offered in Laravel scheduler for interacting with the performance of scheduled tasks. These methods are:

1- sendOutputTo() : To send the output to a file for later inspections.

$schedule->command(‘emails:send)

                                 ->daily()

                                 ->sendOutputTo($filePath);


2- appendOutputTo():
To append the output to a file.

$schedule->command(‘emails:send)

                                   ->daily()

                                   ->appendOutputTo($filePath);


3- emailOutputTo():
To email output to an email id. For this Laravel email services need to be configured.

$schedule->command(‘emails:send)

                                  ->daily()

                                  ->sendOutputTo($filePath)

                                  ->emailOutputTo(‘abcd@email.com’);


4- emailOutputOnFailure():
If scheduled command terminates with a non-zero exit code, use this method.

$schedule->command(‘emails:send)
                                ->daily()

                                ->emailOutputOnFailure(‘abcd@email.com’);

 

 

Leave a Reply