Task Scheduling
Introduction
In the past, you may have written a cron configuration entry for each task you needed to schedule on your server. However, this can quickly become a pain because your task schedule is no longer in source control and you must SSH into your server to view your existing cron entries or add additional entries.
Laravel's command scheduler offers a fresh approach to managing scheduled tasks on your server. The scheduler allows you to fluently and expressively define your command schedule within your Laravel application itself. When using the scheduler, only a single cron entry is needed on your server. Your task schedule is defined in the app/Console/Kernel.php
file's schedule
method. To help you get started, a simple example is defined within the method.
Defining Schedules
You may define all of your scheduled tasks in the schedule
method of your application's App\Console\Kernel
class. To get started, let's take a look at an example. In this example, we will schedule a closure to be called every day at midnight. Within the closure we will execute a database query to clear a table:
1<?php23namespace App\Console;45use Illuminate\Console\Scheduling\Schedule;6use Illuminate\Foundation\Console\Kernel as ConsoleKernel;7use Illuminate\Support\Facades\DB;89class Kernel extends ConsoleKernel10{11 /**12 * Define the application's command schedule.13 *14 * @param \Illuminate\Console\Scheduling\Schedule $schedule15 * @return void16 */17 protected function schedule(Schedule $schedule)18 {19 $schedule->call(function () {20 DB::table('recent_users')->delete();21 })->daily();22 }23}
1<?php23namespace App\Console;45use Illuminate\Console\Scheduling\Schedule;6use Illuminate\Foundation\Console\Kernel as ConsoleKernel;7use Illuminate\Support\Facades\DB;89class Kernel extends ConsoleKernel10{11 /**12 * Define the application's command schedule.13 *14 * @param \Illuminate\Console\Scheduling\Schedule $schedule15 * @return void16 */17 protected function schedule(Schedule $schedule)18 {19 $schedule->call(function () {20 DB::table('recent_users')->delete();21 })->daily();22 }23}
In addition to scheduling using closures, you may also schedule invokable objects. Invokable objects are simple PHP classes that contain an __invoke
method:
1$schedule->call(new DeleteRecentUsers)->daily();
1$schedule->call(new DeleteRecentUsers)->daily();
If you would like to view an overview of your scheduled tasks and the next time they are scheduled to run, you may use the schedule:list
Artisan command:
1php artisan schedule:list
1php artisan schedule:list
Scheduling Artisan Commands
In addition to scheduling closures, you may also schedule Artisan commands and system commands. For example, you may use the command
method to schedule an Artisan command using either the command's name or class.
When scheduling Artisan commands using the command's class name, you may pass an array of additional command-line arguments that should be provided to the command when it is invoked:
1use App\Console\Commands\SendEmailsCommand;23$schedule->command('emails:send Taylor --force')->daily();45$schedule->command(SendEmailsCommand::class, ['Taylor', '--force'])->daily();
1use App\Console\Commands\SendEmailsCommand;23$schedule->command('emails:send Taylor --force')->daily();45$schedule->command(SendEmailsCommand::class, ['Taylor', '--force'])->daily();
Scheduling Queued Jobs
The job
method may be used to schedule a queued job. This method provides a convenient way to schedule queued jobs without using the call
method to define closures to queue the job:
1use App\Jobs\Heartbeat;23$schedule->job(new Heartbeat)->everyFiveMinutes();
1use App\Jobs\Heartbeat;23$schedule->job(new Heartbeat)->everyFiveMinutes();
Optional second and third arguments may be provided to the job
method which specifies the queue name and queue connection that should be used to queue the job:
1use App\Jobs\Heartbeat;23// Dispatch the job to the "heartbeats" queue on the "sqs" connection...4$schedule->job(new Heartbeat, 'heartbeats', 'sqs')->everyFiveMinutes();
1use App\Jobs\Heartbeat;23// Dispatch the job to the "heartbeats" queue on the "sqs" connection...4$schedule->job(new Heartbeat, 'heartbeats', 'sqs')->everyFiveMinutes();
Scheduling Shell Commands
The exec
method may be used to issue a command to the operating system:
1$schedule->exec('node /home/forge/script.js')->daily();
1$schedule->exec('node /home/forge/script.js')->daily();
Schedule Frequency Options
We've already seen a few examples of how you may configure a task to run at specified intervals. However, there are many more task schedule frequencies that you may assign to a task:
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 |
->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 |
->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 |
->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 |
These methods may be combined with additional constraints to create even more finely tuned schedules that only run on certain days of the week. For example, you may schedule a command to run weekly on Monday:
1// Run once per week on Monday at 1 PM...2$schedule->call(function () {3 //4})->weekly()->mondays()->at('13:00');56// Run hourly from 8 AM to 5 PM on weekdays...7$schedule->command('foo')8 ->weekdays()9 ->hourly()10 ->timezone('America/Chicago')11 ->between('8:00', '17:00');
1// Run once per week on Monday at 1 PM...2$schedule->call(function () {3 //4})->weekly()->mondays()->at('13:00');56// Run hourly from 8 AM to 5 PM on weekdays...7$schedule->command('foo')8 ->weekdays()9 ->hourly()10 ->timezone('America/Chicago')11 ->between('8:00', '17:00');
A list of additional schedule constraints may be found below:
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 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 |
Day Constraints
The days
method may be used to limit the execution of a task to specific days of the week. For example, you may schedule a command to run hourly on Sundays and Wednesdays:
1$schedule->command('emails:send')2 ->hourly()3 ->days([0, 3]);
1$schedule->command('emails:send')2 ->hourly()3 ->days([0, 3]);
Alternatively, you may use the constants available on the Illuminate\Console\Scheduling\Schedule
class when defining the days on which a task should run:
1use Illuminate\Console\Scheduling\Schedule;23$schedule->command('emails:send')4 ->hourly()5 ->days([Schedule::SUNDAY, Schedule::WEDNESDAY]);
1use Illuminate\Console\Scheduling\Schedule;23$schedule->command('emails:send')4 ->hourly()5 ->days([Schedule::SUNDAY, Schedule::WEDNESDAY]);
Between Time Constraints
The between
method may be used to limit the execution of a task based on the time of day:
1$schedule->command('emails:send')2 ->hourly()3 ->between('7:00', '22:00');
1$schedule->command('emails:send')2 ->hourly()3 ->between('7:00', '22:00');
Similarly, the unlessBetween
method can be used to exclude the execution of a task for a period of time:
1$schedule->command('emails:send')2 ->hourly()3 ->unlessBetween('23:00', '4:00');
1$schedule->command('emails:send')2 ->hourly()3 ->unlessBetween('23:00', '4:00');
Truth Test Constraints
The when
method may be used to limit the execution of a task based on the result of a given truth test. In other words, if the given closure returns true
, the task will execute as long as no other constraining conditions prevent the task from running:
1$schedule->command('emails:send')->daily()->when(function () {2 return true;3});
1$schedule->command('emails:send')->daily()->when(function () {2 return true;3});
The skip
method may be seen as the inverse of when
. If the skip
method returns true
, the scheduled task will not be executed:
1$schedule->command('emails:send')->daily()->skip(function () {2 return true;3});
1$schedule->command('emails:send')->daily()->skip(function () {2 return true;3});
When using chained when
methods, the scheduled command will only execute if all when
conditions return true
.
Environment Constraints
The environments
method may be used to execute tasks only on the given environments (as defined by the APP_ENV
environment variable):
1$schedule->command('emails:send')2 ->daily()3 ->environments(['staging', 'production']);
1$schedule->command('emails:send')2 ->daily()3 ->environments(['staging', 'production']);
Timezones
Using the timezone
method, you may specify that a scheduled task's time should be interpreted within a given timezone:
1$schedule->command('report:generate')2 ->timezone('America/New_York')3 ->at('2:00')
1$schedule->command('report:generate')2 ->timezone('America/New_York')3 ->at('2:00')
If you are repeatedly assigning the same timezone to all of your scheduled tasks, you may wish to define a scheduleTimezone
method in your App\Console\Kernel
class. This method should return the default timezone that should be assigned to all scheduled tasks:
1/**2 * Get the timezone that should be used by default for scheduled events.3 *4 * @return \DateTimeZone|string|null5 */6protected function scheduleTimezone()7{8 return 'America/Chicago';9}
1/**2 * Get the timezone that should be used by default for scheduled events.3 *4 * @return \DateTimeZone|string|null5 */6protected function scheduleTimezone()7{8 return 'America/Chicago';9}
Remember that some timezones utilize daylight savings time. When daylight saving time changes occur, your scheduled task may run twice or even not run at all. For this reason, we recommend avoiding timezone scheduling when possible.
Preventing Task Overlaps
By default, scheduled tasks will be run even if the previous instance of the task is still running. To prevent this, you may use the withoutOverlapping
method:
1$schedule->command('emails:send')->withoutOverlapping();
1$schedule->command('emails:send')->withoutOverlapping();
In this example, the emails:send
Artisan command will be run every minute if it is not already running. The withoutOverlapping
method is especially useful if you have tasks that vary drastically in their execution time, preventing you from predicting exactly how long a given task will take.
If needed, you may specify how many minutes must pass before the "without overlapping" lock expires. By default, the lock will expire after 24 hours:
1$schedule->command('emails:send')->withoutOverlapping(10);
1$schedule->command('emails:send')->withoutOverlapping(10);
Running Tasks On One Server
To utilize this feature, your application must be using the database
, memcached
, dynamodb
, or redis
cache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server.
If your application's scheduler is running on multiple servers, you may limit a scheduled job to only execute on a single server. For instance, assume you have a scheduled task that generates a new report every Friday night. If the task scheduler is running on three worker servers, the scheduled task will run on all three servers and generate the report three times. Not good!
To indicate that the task should run on only one server, use the onOneServer
method when defining the scheduled task. The first server to obtain the task will secure an atomic lock on the job to prevent other servers from running the same task at the same time:
1$schedule->command('report:generate')2 ->fridays()3 ->at('17:00')4 ->onOneServer();
1$schedule->command('report:generate')2 ->fridays()3 ->at('17:00')4 ->onOneServer();
Background Tasks
By default, multiple tasks scheduled at the same time will execute sequentially based on the order they are defined in your schedule
method. If you have long-running tasks, this may cause subsequent tasks to start much later than anticipated. If you would like to run tasks in the background so that they may all run simultaneously, you may use the runInBackground
method:
1$schedule->command('analytics:report')2 ->daily()3 ->runInBackground();
1$schedule->command('analytics:report')2 ->daily()3 ->runInBackground();
The runInBackground
method may only be used when scheduling tasks via the command
and exec
methods.
Maintenance Mode
Your application's scheduled tasks will not run when the application is in maintenance mode, since we don't want your tasks to interfere with any unfinished maintenance you may be performing on your server. However, if you would like to force a task to run even in maintenance mode, you may call the evenInMaintenanceMode
method when defining the task:
1$schedule->command('emails:send')->evenInMaintenanceMode();
1$schedule->command('emails:send')->evenInMaintenanceMode();
Running The Scheduler
Now that we have learned how to define scheduled tasks, let's discuss how to actually run them on our server. The schedule:run
Artisan command will evaluate all of your scheduled tasks and determine if they need to run based on the server's current time.
So, when using Laravel's scheduler, we only need to add a single cron configuration entry to our server that runs the schedule:run
command every minute. If you do not know how to add cron entries to your server, consider using a service such as Laravel Forge which can manage the cron entries for you:
1* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
1* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Running The Scheduler Locally
Typically, you would not add a scheduler cron entry to your local development machine. Instead, you may use the schedule:work
Artisan command. This command will run in the foreground and invoke the scheduler every minute until you terminate the command:
1php artisan schedule:work
1php artisan schedule:work
Task Output
The Laravel scheduler provides several convenient methods for working with the output generated by scheduled tasks. First, using the sendOutputTo
method, you may send the output to a file for later inspection:
1$schedule->command('emails:send')2 ->daily()3 ->sendOutputTo($filePath);
1$schedule->command('emails:send')2 ->daily()3 ->sendOutputTo($filePath);
If you would like to append the output to a given file, you may use the appendOutputTo
method:
1$schedule->command('emails:send')2 ->daily()3 ->appendOutputTo($filePath);
1$schedule->command('emails:send')2 ->daily()3 ->appendOutputTo($filePath);
Using the emailOutputTo
method, you may email the output to an email address of your choice. Before emailing the output of a task, you should configure Laravel's email services:
1$schedule->command('report:generate')2 ->daily()3 ->sendOutputTo($filePath)
1$schedule->command('report:generate')2 ->daily()3 ->sendOutputTo($filePath)
If you only want to email the output if the scheduled Artisan or system command terminates with a non-zero exit code, use the emailOutputOnFailure
method:
1$schedule->command('report:generate')2 ->daily()
1$schedule->command('report:generate')2 ->daily()
The emailOutputTo
, emailOutputOnFailure
, sendOutputTo
, and appendOutputTo
methods are exclusive to the command
and exec
methods.
Task Hooks
Using the before
and after
methods, you may specify code to be executed before and after the scheduled task is executed:
1$schedule->command('emails:send')2 ->daily()3 ->before(function () {4 // The task is about to execute...5 })6 ->after(function () {7 // The task has executed...8 });
1$schedule->command('emails:send')2 ->daily()3 ->before(function () {4 // The task is about to execute...5 })6 ->after(function () {7 // The task has executed...8 });
The onSuccess
and onFailure
methods allow you to specify code to be executed if the scheduled task succeeds or fails. A failure indicates that the scheduled Artisan or system command terminated with a non-zero exit code:
1$schedule->command('emails:send')2 ->daily()3 ->onSuccess(function () {4 // The task succeeded...5 })6 ->onFailure(function () {7 // The task failed...8 });
1$schedule->command('emails:send')2 ->daily()3 ->onSuccess(function () {4 // The task succeeded...5 })6 ->onFailure(function () {7 // The task failed...8 });
If output is available from your command, you may access it in your after
, onSuccess
or onFailure
hooks by type-hinting an Illuminate\Support\Stringable
instance as the $output
argument of your hook's closure definition:
1use Illuminate\Support\Stringable;23$schedule->command('emails:send')4 ->daily()5 ->onSuccess(function (Stringable $output) {6 // The task succeeded...7 })8 ->onFailure(function (Stringable $output) {9 // The task failed...10 });
1use Illuminate\Support\Stringable;23$schedule->command('emails:send')4 ->daily()5 ->onSuccess(function (Stringable $output) {6 // The task succeeded...7 })8 ->onFailure(function (Stringable $output) {9 // The task failed...10 });
Pinging URLs
Using the pingBefore
and thenPing
methods, the scheduler can automatically ping a given URL before or after a task is executed. This method is useful for notifying an external service, such as Envoyer, that your scheduled task is beginning or has finished execution:
1$schedule->command('emails:send')2 ->daily()3 ->pingBefore($url)4 ->thenPing($url);
1$schedule->command('emails:send')2 ->daily()3 ->pingBefore($url)4 ->thenPing($url);
The pingBeforeIf
and thenPingIf
methods may be used to ping a given URL only if a given condition is true
:
1$schedule->command('emails:send')2 ->daily()3 ->pingBeforeIf($condition, $url)4 ->thenPingIf($condition, $url);
1$schedule->command('emails:send')2 ->daily()3 ->pingBeforeIf($condition, $url)4 ->thenPingIf($condition, $url);
The pingOnSuccess
and pingOnFailure
methods may be used to ping a given URL only if the task succeeds or fails. A failure indicates that the scheduled Artisan or system command terminated with a non-zero exit code:
1$schedule->command('emails:send')2 ->daily()3 ->pingOnSuccess($successUrl)4 ->pingOnFailure($failureUrl);
1$schedule->command('emails:send')2 ->daily()3 ->pingOnSuccess($successUrl)4 ->pingOnFailure($failureUrl);
All of the ping methods require the Guzzle HTTP library. Guzzle is typically installed in all new Laravel projects by default, but, you may manually install Guzzle into your project using the Composer package manager if it has been accidentally removed:
1composer require guzzlehttp/guzzle
1composer require guzzlehttp/guzzle
Events
If needed, you may listen to events dispatched by the scheduler. Typically, event listener mappings will be defined within your application's App\Providers\EventServiceProvider
class:
1/**2 * The event listener mappings for the application.3 *4 * @var array5 */6protected $listen = [7 'Illuminate\Console\Events\ScheduledTaskStarting' => [8 'App\Listeners\LogScheduledTaskStarting',9 ],1011 'Illuminate\Console\Events\ScheduledTaskFinished' => [12 'App\Listeners\LogScheduledTaskFinished',13 ],1415 'Illuminate\Console\Events\ScheduledBackgroundTaskFinished' => [16 'App\Listeners\LogScheduledBackgroundTaskFinished',17 ],1819 'Illuminate\Console\Events\ScheduledTaskSkipped' => [20 'App\Listeners\LogScheduledTaskSkipped',21 ],2223 'Illuminate\Console\Events\ScheduledTaskFailed' => [24 'App\Listeners\LogScheduledTaskFailed',25 ],26];
1/**2 * The event listener mappings for the application.3 *4 * @var array5 */6protected $listen = [7 'Illuminate\Console\Events\ScheduledTaskStarting' => [8 'App\Listeners\LogScheduledTaskStarting',9 ],1011 'Illuminate\Console\Events\ScheduledTaskFinished' => [12 'App\Listeners\LogScheduledTaskFinished',13 ],1415 'Illuminate\Console\Events\ScheduledBackgroundTaskFinished' => [16 'App\Listeners\LogScheduledBackgroundTaskFinished',17 ],1819 'Illuminate\Console\Events\ScheduledTaskSkipped' => [20 'App\Listeners\LogScheduledTaskSkipped',21 ],2223 'Illuminate\Console\Events\ScheduledTaskFailed' => [24 'App\Listeners\LogScheduledTaskFailed',25 ],26];