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 typically defined in your application's routes/console.php
file.
Defining Schedules
You may define all of your scheduled tasks in your application's routes/console.php
file. 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:
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schedule;
Schedule::call(function () {
DB::table('recent_users')->delete();
})->daily();
In addition to scheduling using closures, you may also schedule invokable objects. Invokable objects are simple PHP classes that contain an __invoke
method:
Schedule::call(new DeleteRecentUsers)->daily();
If you prefer to reserve your routes/console.php
file for command definitions only, you may use the withSchedule
method in your application's bootstrap/app.php
file to define your scheduled tasks. This method accepts a closure that receives an instance of the scheduler:
use Illuminate\Console\Scheduling\Schedule;
->withSchedule(function (Schedule $schedule) {
$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:
php 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:
use App\Console\Commands\SendEmailsCommand;
use Illuminate\Support\Facades\Schedule;
Schedule::command('emails:send Taylor --force')->daily();
Schedule::command(SendEmailsCommand::class, ['Taylor', '--force'])->daily();
Scheduling Artisan Closure Commands
If you want to schedule an Artisan command defined by a closure, you may chain the scheduling related methods after the command's definition:
Artisan::command('delete:recent-users', function () {
DB::table('recent_users')->delete();
})->purpose('Delete recent users')->daily();
If you need to pass arguments to the closure command, you may provide them to the schedule
method:
Artisan::command('emails:send {user} {--force}', function ($user) {
// ...
})->purpose('Send emails to the specified user')->schedule(['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:
use App\Jobs\Heartbeat;
use Illuminate\Support\Facades\Schedule;
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:
use App\Jobs\Heartbeat;
use Illuminate\Support\Facades\Schedule;
// Dispatch the job to the "heartbeats" queue on the "sqs" connection...
Schedule::job(new Heartbeat, 'heartbeats', 'sqs')->everyFiveMinutes();
Scheduling Shell Commands
The exec
method may be used to issue a command to the operating system:
use Illuminate\Support\Facades\Schedule;
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. |
->everySecond(); | Run the task every second. |
->everyTwoSeconds(); | Run the task every two seconds. |
->everyFiveSeconds(); | Run the task every five seconds. |
->everyTenSeconds(); | Run the task every ten seconds. |
->everyFifteenSeconds(); | Run the task every fifteen seconds. |
->everyTwentySeconds(); | Run the task every twenty seconds. |
->everyThirtySeconds(); | Run the task every thirty seconds. |
->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($minutes = 0); | Run the task every odd hour. |
->everyTwoHours($minutes = 0); | Run the task every two hours. |
->everyThreeHours($minutes = 0); | Run the task every three hours. |
->everyFourHours($minutes = 0); | Run the task every four hours. |
->everySixHours($minutes = 0); | 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. |
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:
use Illuminate\Support\Facades\Schedule;
// Run once per week on Monday at 1 PM...
Schedule::call(function () {
// ...
})->weekly()->mondays()->at('13:00');
// Run hourly from 8 AM to 5 PM on weekdays...
Schedule::command('foo')
->weekdays()
->hourly()
->timezone('America/Chicago')
->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:
use Illuminate\Support\Facades\Schedule;
Schedule::command('emails:send')
->hourly()
->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:
use Illuminate\Support\Facades;
use Illuminate\Console\Scheduling\Schedule;
Facades\Schedule::command('emails:send')
->hourly()
->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:
Schedule::command('emails:send')
->hourly()
->between('7:00', '22:00');
Similarly, the unlessBetween
method can be used to exclude the execution of a task for a period of time:
Schedule::command('emails:send')
->hourly()
->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:
Schedule::command('emails:send')->daily()->when(function () {
return true;
});
The skip
method may be seen as the inverse of when
. If the skip
method returns true
, the scheduled task will not be executed:
Schedule::command('emails:send')->daily()->skip(function () {
return true;
});
When using chained when
methods, the scheduled command will only execute if all when
conditions return true
.