任务调度
这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。
任务调度
简介
过去,你可能需要在服务器上为每一个调度任务去创建一个 cron 配置项。但是,这种方式很快会变得麻烦,因为你的任务调度已不再受源代码控制,而且你必须通过 SSH 登录到服务器才能查看现有的 cron 配置项或添加其他配置项。
Laravel 的命令调度器提供了一种全新的方法来管理服务器上的定时任务。调度器允许你直接在 Laravel 应用内部中流畅且直观地定义你的命令调度。使用这个调度器时,你的服务器上只需要配置一条 cron 记录就可以了。你的任务调度通常在应用程序的 routes/console.php 文件中定义。
定义调度
你可以在应用程序的 routes/console.php 文件中定义所有计划任务。首先,我们来看一个示例。在此示例中,我们将调度一个闭包,使其每天午夜执行。在闭包中,我们将执行一个数据库查询来清空某张表:
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schedule;
Schedule::call(function () {
DB::table('recent_users')->delete();
})->daily();
除了使用闭包进行调度外,你还可以调度 invokable 对象. Invokable 对象是包含 __invoke 方法的简单 PHP 类:
Schedule::call(new DeleteRecentUsers)->daily();
如果你倾向于仅将 routes/console.php 文件用于命令定义,那么可以在应用程序的 bootstrap/app.php 文件中使用 withSchedule 方法来定义定时任务。该方法接受一个闭包,此闭包会接收调度器的一个实例:
use Illuminate\Console\Scheduling\Schedule;
->withSchedule(function (Schedule $schedule) {
$schedule->call(new DeleteRecentUsers)->daily();
})
如果你想查看调度任务的概览和下一次运行时间,可以使用 schedule:list Artisan 命令:
php artisan schedule:list
调度 Artisan 命令
除了调度闭包,你还可以调度 Artisan 命令 和系统命令。例如,你可以使用 command 方法通过命令名称或类来调度 Artisan 命令。
当使用命令的类名来调度 Artisan 命令时,你可以传递一个额外的命令行参数数组,这些参数会在命令被调用时提供给该命令:
use App\Console\Commands\SendEmailsCommand;
use Illuminate\Support\Facades\Schedule;
Schedule::command('emails:send Taylor --force')->daily();
Schedule::command(SendEmailsCommand::class, ['Taylor', '--force'])->daily();
调度 Artisan 闭包命令
如果你想调度一个由闭包定义的 Artisan 命令,可以在命令定义后链式调用与调度相关的方法:
Artisan::command('delete:recent-users', function () {
DB::table('recent_users')->delete();
})->purpose('Delete recent users')->daily();
如果你需要向闭包命令传递参数,可以将参数提供给 schedule 方法:
Artisan::command('emails:send {user} {--force}', function ($user) {
// ...
})->purpose('Send emails to the specified user')->schedule(['Taylor', '--force'])->daily();
调度队列作业
job 方法可用于调度队列作业。该方法提供了一种便捷方式来调度队列作业,而无需使用 call 方法定义闭包来将作业加入队列:
use App\Jobs\Heartbeat;
use Illuminate\Support\Facades\Schedule;
Schedule::job(new Heartbeat)->everyFiveMinutes();
可以向 job 方法提供可选的第二个和第三个参数,它们分别指定应使用的队列名称和队列连接,用于将作业加入队列:
use App\Jobs\Heartbeat;
use Illuminate\Support\Facades\Schedule;
// 将作业分发到「sqs」连接上的「heartbeats」队列...
Schedule::job(new Heartbeat, 'heartbeats', 'sqs')->everyFiveMinutes();
调度 Shell 命令
exec 方法可用于向操作系统发出命令:
use Illuminate\Support\Facades\Schedule;
Schedule::exec('node /home/forge/script.js')->daily();
调度频率选项
我们前面已经看过几个如何配置任务在指定时间间隔运行的示例。不过,你还可以为任务分配更多种不同的调度频率:
| Method | Description | | ---------------------------------- | -------------------------------------------------------- | | `->cron('* * * * *');` | 按自定义 Cron 计划运行任务。 | | `->everySecond();` | 每秒运行一次任务。 | | `->everyTwoSeconds();` | 每 2 秒运行一次任务。 | | `->everyFiveSeconds();` | 每 5 秒运行一次任务。 | | `->everyTenSeconds();` | 每 10 秒运行一次任务。 | | `->everyFifteenSeconds();` | 每 15 秒运行一次任务。 | | `->everyTwentySeconds();` | 每 20 秒运行一次任务。 | | `->everyThirtySeconds();` | 每 30 秒运行一次任务。 | | `->everyMinute();` | 每分钟运行一次任务。 | | `->everyTwoMinutes();` | 每 2 分钟运行一次任务。 | | `->everyThreeMinutes();` | 每 3 分钟运行一次任务。 | | `->everyFourMinutes();` | 每 4 分钟运行一次任务。 | | `->everyFiveMinutes();` | 每 5 分钟运行一次任务。 | | `->everyTenMinutes();` | 每 10 分钟运行一次任务。 | | `->everyFifteenMinutes();` | 每 15 分钟运行一次任务。 | | `->everyThirtyMinutes();` | 每 30 分钟运行一次任务。 | | `->hourly();` | 每小时运行一次任务。 | | `->hourlyAt(17);` | 每小时的 17 分钟时运行一次任务。 | | `->everyOddHour($minutes = 0);` | 每奇数小时运行一次任务。 | | `->everyTwoHours($minutes = 0);` | 每 2 小时运行一次任务。 | | `->everyThreeHours($minutes = 0);` | 每 3 小时运行一次任务。 | | `->everyFourHours($minutes = 0);` | 每 4 小时运行一次任务。 | | `->everySixHours($minutes = 0);` | 每 6 小时运行一次任务。 | | `->daily();` | 每天午夜 12 点(00:00)运行一次任务。 | | `->dailyAt('13:00');` | 每天 13:00 运行一次任务。 | | `->twiceDaily(1, 13);` | 每天 1:00 和 13:00 运行一次任务。 | | `->twiceDailyAt(1, 13, 15);` | 每天 1:15 和 13:15 运行一次任务。 | | `->daysOfMonth([1, 10, 20]);` | 在每月的特定日期运行一次任务。 | | `->weekly();` | 每周日 00:00 运行一次任务。 | | `->weeklyOn(1, '8:00');` | 每周一 8:00 运行一次任务。 | | `->monthly();` | 每月第一天 00:00 运行一次任务。 | | `->monthlyOn(4, '15:00');` | 每月 4 日 15:00 运行一次任务。 | | `->twiceMonthly(1, 16, '13:00');` | 每月 1 日和 16 日 13:00 运行一次任务。 | | `->lastDayOfMonth('15:00');` | 每月最后一天 15:00 运行一次任务。 | | `->quarterly();` | 每个季度的第一天 00:00 运行一次任务。 | | `->quarterlyOn(4, '14:00');` | 每个季度的第四天 14:00 运行一次任务。 | | `->yearly();` | 每年的第一天 00:00 运行一次任务。 | | `->yearlyOn(6, 1, '17:00');` | 每年 6 月 1 日 17:00 运行一次任务。 | | `->timezone('America/New_York');` | 设置任务时区。 |
这些方法可以与其他约束条件结合使用,从而创建出更精细的调度,使其仅在一周中的特定日期运行。例如,你可以将命令安排为每周一运行:
use Illuminate\Support\Facades\Schedule;
// 每周运行一次,时间为周一下午 1 点...
Schedule::call(function () {
// ...
})->weekly()->mondays()->at('13:00');
// 在工作日上午 8 点至下午 5 点之间,每小时运行一次...
Schedule::command('foo')
->weekdays()
->hourly()
->timezone('America/Chicago')
->between('8:00', '17:00');
其他调度约束条件列表如下:
| Method | Description | | ---------------------------------------- | ------------------------------------------------------ | | `->weekdays();` | 将任务限制为工作日。 | | `->weekends();` | 将任务限制到周末。 | | `->sundays();` | 将任务限制到周日。 | | `->mondays();` | 将任务限制在周一。 | | `->tuesdays();` | 将任务限制在周二。 | | `->wednesdays();` | 将任务限制在周三。 | | `->thursdays();` | 将任务限制在周四。 | | `->fridays();` | 将任务限制在周五。 | | `->saturdays();` | 将任务限制在周六。 | | `->days(array\|mixed);` | 将任务限制在特定日期。 | | `->between($startTime, $endTime);` | 限制任务在开始时间和结束时间之间运行。 | | `->unlessBetween($startTime, $endTime);` | 限制任务不在开始时间和结束时间之间运行。 | | `->when(Closure);` | 根据真值测试限制任务。 | | `->environments($env);` | 将任务限制在特定环境中。 |
Day Constraints
days 方法可以用于约束任务在每周的指定日期执行。例如,你可以调度命令在周日和周三每小时运行一次:
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.
Environment Constraints
The environments method may be used to execute tasks only on the given environments (as defined by the APP_ENV environment variable):
Schedule::command('emails:send')
->daily()
->environments(['staging', 'production']);
Timezones
Using the timezone method, you may specify that a scheduled task's time should be interpreted within a given timezone:
use Illuminate\Support\Facades\Schedule;
Schedule::command('report:generate')
->timezone('America/New_York')
->at('2:00')
If you are repeatedly assigning the same timezone to all of your scheduled tasks, you can specify which timezone should be assigned to all schedules by defining a schedule_timezone option within your application's app configuration file:
'timezone' => 'UTC',
'schedule_timezone' => 'America/Chicago',
[!WARNING]
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:
use Illuminate\Support\Facades\Schedule;
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:
Schedule::command('emails:send')->withoutOverlapping(10);
Behind the scenes, the withoutOverlapping method utilizes your application's cache to obtain locks. If necessary, you can clear these cache locks using the schedule:clear-cache Artisan command. This is typically only necessary if a task becomes stuck due to an unexpected server problem.
Running Tasks on One Server
[!WARNING]
To utilize this feature, your application must be using thedatabase,memcached,dynamodb, orrediscache 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:
use Illuminate\Support\Facades\Schedule;
Schedule::command('report:generate')
->fridays()
->at('17:00')
->onOneServer();
You may use the useCache method to customize the cache store used by the scheduler to obtain the atomic locks necessary for single-server tasks:
Schedule::useCache('database');
Naming Single Server Jobs
Sometimes you may need to schedule the same job to be dispatched with different parameters, while still instructing Laravel to run each permutation of the job on a single server. To accomplish this, you may assign each schedule definition a unique name via the name method:
Schedule::job(new CheckUptime('https://laravel.com'))
->name('check_uptime:laravel.com')
->everyFiveMinutes()
->onOneServer();
Schedule::job(new CheckUptime('https://vapor.laravel.com'))
->name('check_uptime:vapor.laravel.com')
->everyFiveMinutes()
->onOneServer();
Similarly, scheduled closures must be assigned a name if they are intended to be run on one server:
Schedule::call(fn () => User::resetApiRequestCount())
->name('reset-api-request-count')
->daily()
->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:
use Illuminate\Support\Facades\Schedule;
Schedule::command('analytics:report')
->daily()
->runInBackground();
[!WARNING]
TherunInBackgroundmethod may only be used when scheduling tasks via thecommandandexecmethods.
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:
Schedule::command('emails:send')->evenInMaintenanceMode();
Pausing Scheduled Tasks
You may temporarily pause scheduled task processing without changing your deployed code by using the schedule:pause Artisan command:
php artisan schedule:pause
While the scheduler is paused, no scheduled tasks will run. You may resume scheduled task processing using the schedule:continue command:
php artisan schedule:continue
If a task should still run while the scheduler is paused, you may mark it with the evenWhenPaused method:
Schedule::command('emails:send')->evenWhenPaused();
Schedule Groups
When defining multiple scheduled tasks with similar configurations, you can use Laravel's task grouping feature to avoid repeating the same settings for each task. Grouping tasks simplifies your code and ensures consistency across related tasks.
To create a group of scheduled tasks, invoke the desired task configuration methods, followed by the group method. The group method accepts a closure that is responsible for defining the tasks that share the specified configuration:
use Illuminate\Support\Facades\Schedule;
Schedule::daily()
->onOneServer()
->timezone('America/New_York')
->group(function () {
Schedule::command('emails:send --force');
Schedule::command('emails:prune');
});
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 managed platform such as Laravel Cloud which can manage the scheduled task execution for you:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Sub-Minute Scheduled Tasks
On most operating systems, cron jobs are limited to running a maximum of once per minute. However, Laravel's scheduler allows you to schedule tasks to run at more frequent intervals, even as often as once per second:
use Illuminate\Support\Facades\Schedule;
Schedule::call(function () {
DB::table('recent_users')->delete();
})->everySecond();
When sub-minute tasks are defined within your application, the schedule:run command will continue running until the end of the current minute instead of exiting immediately. This allows the command to invoke all required sub-minute tasks throughout the minute.
Since sub-minute tasks that take longer than expected to run could delay the execution of later sub-minute tasks, it is recommended that all sub-minute tasks dispatch queued jobs or background commands to handle the actual task processing:
use App\Jobs\DeleteRecentUsers;
Schedule::job(new DeleteRecentUsers)->everyTenSeconds();
Schedule::command('users:delete')->everyTenSeconds()->runInBackground();
Interrupting Sub-Minute Tasks
As the schedule:run command runs for the entire minute of invocation when sub-minute tasks are defined, you may sometimes need to interrupt the command when deploying your application. Otherwise, an instance of the schedule:run command that is already running would continue using your application's previously deployed code until the current minute ends.
To interrupt in-progress schedule:run invocations, you may add the schedule:interrupt command to your application's deployment script. This command should be invoked after your application is finished deploying:
php artisan schedule:interrupt
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. When sub-minute tasks are defined, the scheduler will continue running within each minute to process those tasks:
php 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:
use Illuminate\Support\Facades\Schedule;
Schedule::command('emails:send')
->daily()
->sendOutputTo($filePath);
If you would like to append the output to a given file, you may use the appendOutputTo method:
Schedule::command('emails:send')
->daily()
->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:
Schedule::command('report:generate')
->daily()
->sendOutputTo($filePath)
->emailOutputTo('taylor@example.com');
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:
Schedule::command('report:generate')
->daily()
->emailOutputOnFailure('taylor@example.com');
[!WARNING]
TheemailOutputTo,emailOutputOnFailure,sendOutputTo, andappendOutputTomethods are exclusive to thecommandandexecmethods.
Task Hooks
Using the before and after methods, you may specify code to be executed before and after the scheduled task is executed:
use Illuminate\Support\Facades\Schedule;
Schedule::command('emails:send')
->daily()
->before(function () {
// The task is about to execute...
})
->after(function () {
// The task has executed...
});
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:
Schedule::command('emails:send')
->daily()
->onSuccess(function () {
// The task succeeded...
})
->onFailure(function () {
// The task failed...
});
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:
use Illuminate\Support\Stringable;
Schedule::command('emails:send')
->daily()
->onSuccess(function (Stringable $output) {
// The task succeeded...
})
->onFailure(function (Stringable $output) {
// The task failed...
});
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:
Schedule::command('emails:send')
->daily()
->pingBefore($url)
->thenPing($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:
Schedule::command('emails:send')
->daily()
->pingOnSuccess($successUrl)
->pingOnFailure($failureUrl);
The pingBeforeIf,thenPingIf,pingOnSuccessIf, and pingOnFailureIf methods may be used to ping a given URL only if a given condition is true:
Schedule::command('emails:send')
->daily()
->pingBeforeIf($condition, $url)
->thenPingIf($condition, $url);
Schedule::command('emails:send')
->daily()
->pingOnSuccessIf($condition, $successUrl)
->pingOnFailureIf($condition, $failureUrl);
Events
Laravel dispatches a variety of events during the scheduling process. You may define listeners for any of the following events:
| Event Name | | ----------------------------------------------------------- | | `Illuminate\Console\Events\ScheduledTaskStarting` | | `Illuminate\Console\Events\ScheduledTaskFinished` | | `Illuminate\Console\Events\ScheduledBackgroundTaskFinished` | | `Illuminate\Console\Events\ScheduledTaskSkipped` | | `Illuminate\Console\Events\ScheduledTaskFailed` |
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
Laravel 13 中文文档
关于 LearnKu
推荐文章: