Cadence 经过 史蒂夫·鲍曼 takes a different approach to scheduling in Laravel. Rather than centralising all timed tasks in a single scheduler file, it lets you attach one or many schedules directly to individual Eloquent model instances, each with its own expression and timezone, and fires events when they're due.
工作原理
After installing the package and publishing the migration, you get a
schedules
table that holds a polymorphic reference to any model, the schedule expression, an optional timezone, and precomputed
next_run_at
/
last_run_at
timestamps.
添加
Schedulable
接口和
HasSchedules
trait to any model you want to schedule:
使用
DirectoryTree\Cadence\HasSchedules
;使用
DirectoryTree\Cadence\Schedulable
;班级
订阅
延伸
模型
实现
Schedulable{
使用
HasSchedules
;}
Then attach a schedule to a model instance. Cadence ships with drivers for cron expressions and RRULE patterns, and you pick which libraries to install:
# For cron expressions作曲家
要求
dragonmantank/cron-expression# For RRULE (pick one)作曲家
要求
rlanvin/php-rrule# 或者作曲家
要求
simshaun/recurr
A cron-based schedule is straightforward:
使用
DirectoryTree\Cadence\Drivers\CronSchedule
;// Bill this subscription every month on the 1st at midnight$subscription
->
addSchedule
(
新的
CronSchedule
(
'0 0 1 * *'
));
For more expressive recurrence, RRULE gives you a lot more control over things that are awkward to express in cron:
使用
DirectoryTree\Cadence\Drivers\RruleSchedule
;// Every two weeks on Tuesday and Thursday$subscription
->
addSchedule
(
新的
RruleSchedule
(
'FREQ=WEEKLY;INTERVAL=2;BYDAY=TU,TH'
));
Schedules are timezone-aware, so users in different regions get the right local time:
$subscription
->
addSchedule
(
新的
CronSchedule
(
'0 8 * * 1'
,
'Australia/Sydney'
)
// Monday 8am Sydney time(英文):
Dispatching and Reacting
Cadence provides a
schedules:run
Artisan command that you register with Laravel's scheduler to run every minute:
// routes/console.php日程
::
命令
(
'schedules:run'
)
->
不重叠
()
->
每分钟
();
Each time it runs, it finds all records where
next_run_at
is past due, fires a
ScheduleTriggered
event for each one, and advances the next occurrence. Your application reacts through a listener:
使用
DirectoryTree\Cadence\Events\ScheduleTriggered
;班级
ProcessDueSubscription{
民众
功能
处理
(
ScheduleTriggered
$event)
:
空白{$subscription
=
$事件
->
日程
->
schedulable;$subscription
->
processRenewal
();}}
The event carries the schedule record, giving you access to the parent model, the expression, and timestamps for branching on model type or logging what ran and when.
可扩展性
If neither cron nor RRULE fits, you can implement a custom driver by extending the base
Schedule
class and implementing
resolveNextOccurrence()
, which receives a
CarbonInterface
and returns the next occurrence. Drivers are registered by name, so swapping or extending them later is straightforward.
You can learn more and view the source code on GitHub 。







