Task Scheduling in Laravel

Tram Ho

Introduce

  • In the past, you may have created a Cron for a task that you want to schedule to run on your server. However, it will be quite annoying if you want to change or add new schedules when you have to SSH to your server to do this.
  • Laravel’s scheduler command allows you to define your schedule easily right within Laravel itself. When using the scheduler, you only need one Cron command on your server. Your schedule will be defined in the schedule method on the app/Console/Kernel.php file. To get you started, a simple example is defined in the method.
  • Example: With Task Scheduling, you can easily schedule tasks like sending out daily emails, deleting old records, updating data from external sources and much more. Laravel provides a simple syntax for defining tasks and scheduling them, ensuring that tasks are performed on time and in the right way.

1.Initialize Schedules

You can initialize scheduled tasks in the schedule method in the AppConsoleKernel class. Here is an example of a schedule task that runs a query to delete a table every day:

In addition to using Closure when declaring a schedule, you can also call any PHP class that has an __invoke() method:

To see an overview of Scheduled tasks and the next time it will run you can use the following command:

image.png

2. Scheduling for artisan command

You can also schedule commands to run by passing the command directly or passing the command’s class:

When using the class name, the arguments you want to pass will have to be in the form of an array

3. Scheduling Queued Jobs

To schedule a job to be placed on the queue, you use the job method. Examples are as follows:

4. Scheduling Shell Commands

In addition, you can also schedule any command:

5. Custom Scheduling Time Options

Frequency options:

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

In addition to the options above, you can combine the following constraints to create a tighter schedule:

Methoddescription
->weekdays();Limit the task to weekdays
->weekends();Limit the tasks 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 days
->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

For example:

Schedule on weekdays : Run hourly on Sunday and Wednesday

Between 1 time interval : Run hourly between 7:00 and 22:00

Condition-based : When the condition is true, execute

Based on the environment

6. Prevent overlapping tasks

By default, scheduled tasks will run without waiting for the previous task to finish running or not. So to prevent that you can use the withoutOverlapping method:

By default, it will be 24 hours after the previous task finishes, then run to the next task, so you can declare an optional time:

  • This actually uses the cache to store the lock variable. Something like when a task is run a lock variable will be cached, after completion, that variable will be deleted. If the next task runs, it will need to check if the lock variable exists or not before it can continue.
  • So if a task is stuck, you can clear the cache to fix it: schedule:clear-cache

It is possible to run the schedule even when the application is in maintenance mode: $schedule->command('emails:send')->evenInMaintenanceMode();

7. Run schedule

Server environment : to start running the schedule on the server environment you use the command with the following syntax:

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

image.png

Local environment : Just run the following artisan command:

php artisan schedule:work

Share the news now

Source : Viblo