目录
- ⒈ runInBackground 和 withoutOverlapping
- ⑴ runInBackground() 方法
- ⑵ withoutOverlapping() 方法
- ⒉ mutex 互斥锁
- ⑴ 超时时间
- ⑵ 回调方法
Laravel 的 console 命令行极大地简化了 PHP 定时任务的配置与执行过程。相较于传统的 crontab 方式,Laravel 提供了更便捷的管理手段,但同时也面临一个常见问题:通过 crontab 设置的定时任务难以有效防止任务的交叠运行。
所谓任务的交叠运行,是指当某个定时任务的执行时间较长,而 crontab 设定的运行周期较短时,前一个任务尚未结束,系统便启动了新的任务实例去执行相同的操作。如果程序内部未妥善处理数据一致性逻辑,多个任务实例同时操作同一份数据,极有可能引发严重的数据错误或系统故障。
⒈ runInBackground 和 withoutOverlapping
为了解决上述问题,Laravel 提供了两种关键机制:一是通过 withoutOverlapping() 方法防止任务交叠运行;二是通过 runInBackground() 方法支持多任务在后台并行执行,从而提升整体效率。
⑴ runInBackground() 方法
在 Laravel 的 console 命令行体系中,每一个命令都对应一个 Event 对象。\App\Console\Kernel 类中的 schedule() 方法主要负责将这些命令行代表的 Event 注册到 Illuminate\Console\Scheduling\Schedule 类的 $events 属性集合中,完成调度的初始化配置。
// namespace \Illuminate\Console\Scheduling\Schedule
public function command($command, array $parameters = [])
{
if (class_exists($command)) {
$command = Container::getInstance()->make($command)->getName();
}
return $this->exec(
Application::formatCommandString($command), $parameters
);
}
public function exec($command, array $parameters = [])
{
if (count($parameters)) {
$command .= ' '.$this->compileParameters($parameters);
}
$this->events[] = $event = new Event($this->eventMutex, $command, $this->timezone);
return $event;
}
Event 对象的运行方式分为两种:Foreground(前台)和 Background(后台)。两者的核心区别在于是否允许并行执行。默认情况下,Event 以 Foreground 方式运行,此时多个 Event 按顺序串行执行,后续 Event 必须等待前一个 Event 完全结束后才能启动。
在实际应用场景中,往往希望多个 Event 能够并行执行以提高效率。此时,需要调用 Event 的 runInBackground() 方法将其运行模式切换为 Background。Laravel 框架对这两种模式的差异处理主要体现在命令行组装策略和回调方法的调用时机上。
// namespace \Illuminate\Console\Scheduling\Event
protected function runCommandInForeground(Container $container)
{
$this->callBeforeCallbacks($container);
$this->exitCode = Process::fromShellCommandline($this->buildCommand(), base_path(), null, null, null)->run();
$this->callAfterCallbacks($container);
}
protected function runCommandInBackground(Container $container)
{
$this->callBeforeCallbacks($container);
Process::fromShellCommandline($this->buildCommand(), base_path(), null, null, null)->run();
}
public function buildCommand()
{
return (new CommandBuilder)->buildCommand($this);
}
// namespace Illuminate\Console\Scheduling\CommandBuilder
public function buildCommand(Event $event)
{
if ($event->runInBackground) {
return $this->buildBackgroundCommand($event);
}
return $this->buildForegroundCommand($event);
}
protected function buildForegroundCommand(Event $event)
{
$output = ProcessUtils::escapeArgument($event->output);
return $this->ensureCorrectUser(
$event, $event->command.($event->shouldAppendOutput ? ' >> ' : ' > ').$output.' 2>&1'
);
}
protected function buildBackgroundCommand(Event $event)
{
$output = ProcessUtils::escapeArgument($event->output);
$redirect = $event->shouldAppendOutput ? ' >> ' : ' > ';
$finished = Application::formatCommandString('schedule:finish').' "'.$event->mutexName().'"';
if (windows_os()) {
return 'start /b cmd /c "('.$event->command.' & '.$finished.' "%errorlevel%")'.$redirect.$output.' 2>&1"';
}
return $this->ensureCorrectUser($event,
'('.$event->command.$redirect.$output.' 2>&1 ; '.$finished.' "$?") > '
.ProcessUtils::escapeArgument($event->getDefaultOutput()).' 2>&1 &'
);
}
从代码层面分析,采用 Background 方式运行的 Event,其生成的命令行末尾会追加 & 符号,该符号指示操作系统将进程放入后台运行。此外,Foreground 模式的回调方法是同步执行的,而 Background 模式的 after 回调则通过专门的 schedule:finish 命令行异步触发。
⑵ withoutOverlapping() 方法
在配置 Event 的运行周期时,由于业务场景的动态变化,某些特定 Event 可能需要较长时间才能完成,甚至可能跨越下一个预定执行时间点仍未结束。若不对此进行干预,会导致相同 Event 的多重实例同时运行。若这些实例涉及数据修改且缺乏幂等性处理,后果将十分严重。为此,Event 提供了 withoutOverlapping() 方法,通过将 withoutOverlapping 属性设为 TRUE,在执行前检查是否存在正在运行的同类 Event,若存在则跳过新任务的执行。
// namespace Illuminate\Console\Scheduling\Event
public function withoutOverlapping($expiresAt = 1440)
{
$this->withoutOverlapping = true;
$this->expiresAt = $expiresAt;
return $this->then(function () {
$this->mutex->forget($this);
})->skip(function () {
return $this->mutex->exists($this);
});
}
public function run(Container $container)
{
if ($this->withoutOverlapping &&
! $this->mutex->create($this)) {
return;
}
$this->runInBackground
? $this->runCommandInBackground($container)
: $this->runCommandInForeground($container);
}
⒉ mutex 互斥锁
调用 withoutOverlapping() 方法不仅实现了防重叠功能,还附带了两个重要特性:一是设置超时时间,默认为 24 小时;二是配置 Event 相关的回调方法,用于锁的释放与状态检查。
⑴ 超时时间
首先关注超时时间机制。这里的超时并非指 Event 本身的执行超时,而是指 Event 内部 mutex 属性的过期时间。当向 Schedule 的 $events 注册 Event 时,会调用 exec() 方法创建 Event 对象,并传入 eventMutex 参数,这便是 Event 中的 mutex 属性。该 mutex 由 Schedule 通过实例化 CacheEventMutex 类来创建。
// namespace \Illuminate\Console\Scheduling\Schedule
$this->eventMutex = $container->bound(EventMutex::class)
? $container->make(EventMutex::class)
: $container->make(CacheEventMutex::class);
设置了 withoutOverlapping 的 Event 在执行前,会尝试获取 mutex 互斥锁。若获取失败,则 Event 不会执行。这一操作通过调用 mutex 的 create() 方法完成。CacheEventMutex 实例化时需注入 \Illuminate\Contracts\Cache\Factory 类型的实例,通常最终传入的是 \Illuminate\Cache\CacheManager 实例。在调用 create() 获取锁时,还需通过 store() 方法指定存储引擎。
// namespace \Illuminate\Foundation\Console\Kernel
protected function defineConsoleSchedule()
{
$this->app->singleton(Schedule::class, function ($app) {
return tap(new Schedule($this->scheduleTimezone()), function ($schedule) {
$this->schedule($schedule->useCache($this->scheduleCache()));
});
});
}
protected function scheduleCache()
{
return Env::get('SCHEDULE_CACHE_DRIVER');
}
// namespace \Illuminate\Console\Scheduling\Schedule
public function useCache($store)
{
if ($this->eventMutex instanceof CacheEventMutex) {
$this->eventMutex->useStore($store);
}
/* ... ... */
return $this;
}
// namespace \Illuminate\Console\Scheduling\CacheEventMutex
public function create(Event $event)
{
return $this->cache->store($this->store)->add(
$event->mutexName(), true, $event->expiresAt * 60
);
}
// namespace \Illuminate\Cache\CacheManager
public function store($name = null)
{
$name = $name ?: $this->getDefaultDriver();
return $this->stores[$name] = $this->get($name);
}
public function getDefaultDriver()
{
return $this->app['config']['cache.default'];
}
protected function get($name)
{
return $this->stores[$name] ?? $this->resolve($name);
}
protected function resolve($name)
{
$config = $this->getConfig($name);
if (is_null($config)) {
throw new InvalidArgumentException("Cache store [{$name}] is not defined.");
}
if (isset($this->customCreators[$config['driver']])) {
return $this->callCustomCreator($config);
} else {
$driverMethod = 'create'.ucfirst($config['driver']).'Driver';
if (method_exists($this, $driverMethod)) {
return $this->{$driverMethod}($config);
} else {
throw new InvalidArgumentException("Driver [{$config['driver']}] is not supported.");
}
}
}
protected function getConfig($name)
{
return $this->app['config']["cache.stores.{$name}"];
}
protected function createFileDriver(array $config)
{
return $this->repository(new FileStore($this->app['files'], $config['path'], $config['permission'] ?? null));
}
在 Schedule 初始化阶段,会指定 eventMutex 的存储引擎,默认读取环境变量 SCHEDULE_CACHE_DRIVER 的值。然而,该环境变量通常不存在,导致 useCache() 参数为空,进而 eventMutex 的 store 属性也为空。因此,在 create() 方法中调用 store() 设置引擎时,参数同样为空。
当 store() 方法接收空参数时,系统将使用应用的默认存储引擎。在未做特殊修改的情况下,默认 cache 存储引擎为 file。随后,系统获取默认存储引擎的配置信息(包括引擎类型、存储路径、连接信息等),并实例化相应的存储引擎。对于 file 引擎,最终实例化的是 \Illuminate\Cache\FileStore 对象。
存储引擎设定完毕后,紧接着调用 add() 方法来获取互斥锁。由于 store() 返回的是 \Illuminate\Contracts\Cache\Repository 类型的实例,因此实际调用的是 Illuminate\Cache\Repository 类中的 add() 方法。
// namespace \Illuminate\Cache\Repository
public function add($key, $value, $ttl = null)
{
if ($ttl !== null) {
if ($this->getSeconds($ttl) <= 0) {
return false;
}
if (method_exists($this->store, 'add')) {
$seconds = $this->getSeconds($ttl);
return $this->store->add(
$this->itemKey($key), $value, $seconds
);
}
}
if (is_null($this->get($key))) {
return $this->put($key, $value, $ttl);
}
return false;
}
public function get($key, $default = null)
{
if (is_array($key)) {
return $this->many($key);
}
$value = $this->store->get($this->itemKey($key));
if (is_null($value)) {
$this->event(new CacheMissed($key));
$value = value($default);
} else {
$this->event(new CacheHit($key, $value));
}
return $value;
}
// namespace \Illuminate\Cache\FileStore
public function get($key)
{
return $this->getPayload($key)['data'] ?? null;
}
protected function getPayload($key)
{
$path = $this->path($key);
try {
$expire = substr(
$contents = $this->files->get($path, true), 0, 10
);
} catch (Exception $e) {
return $this->emptyPayload();
}
if ($this->currentTime() >= $expire) {
$this->forget($key);
return $this->emptyPayload();
}
try {
$data = unserialize(substr($contents, 10));
} catch (Exception $e) {
$this->forget($key);
return $this->emptyPayload();
}
$time = $expire - $this->currentTime();
return compact('data', 'time');
}
需明确的是,互斥锁的本质是写文件操作。若目标文件不存在、内容为空或文件中存储的过期时间戳小于当前时间,则互斥锁可顺利获取;否则获取失败。写入文件的内容格式固定为 timestampb:1 。
所谓的超时时间与此处的 timestamp 值密切相关。获取互斥锁时的当前时间戳,加上配置的超时秒数,即构成此处 timestamp 的值。
由于 FileStore 类中并未定义 add() 方法,程序会转而尝试调用 get() 方法读取文件内容。若 get() 返回 NULL,表明成功获取互斥锁,随后调用 FileStore 的 put() 方法写入文件;若返回非空,说明已有相同 Event 正在运行,不再执行新任务。在调用 put() 写入文件时,首先根据参数计算 eventMutex 的超时秒数,再执行写入操作。
// namespace \Illuminate\Cache\Repository
public function put($key, $value, $ttl = null)
{
/* ... ... */
$seconds = $this->getSeconds($ttl);
if ($seconds <= 0) {
return $this->forget($key);
}
$result = $this->store->put($this->itemKey($key), $value, $seconds);
if ($result) {
$this->event(new KeyWritten($key, $value, $seconds));
}
return $result;
}
// namespace \Illuminate\Cache\FileStore
public function put($key, $value, $seconds)
{
$this->ensureCacheDirectoryExists($path = $this->path($key));
$result = $this->files->put(
$path, $this->expiration($seconds).serialize($value), true
);
if ($result !== false && $result > 0) {
$this->ensureFileHasCorrectPermissions($path);
return true;
}
return false;
}
protected function path($key)
{
$parts = array_slice(str_split($hash = sha1($key), 2), 0, 2);
return $this->directory.'/'.implode('/', $parts).'/'.$hash;
}
// namespace \Illuminate\Console\Scheduling\Schedule
public function mutexName()
{
return 'framework'.DIRECTORY_SEPARATOR.'schedule-'.sha1($this->expression.$this->command);
}
这里重点说明 $key 及文件路径的生成逻辑。$key 通过调用 Event 的 mutexName() 方法生成,依赖于 Event 的 $expression(运行周期)和 $command(命令行)属性。其中 $command 是在调用 $schedule->command() 时传入并经过格式化处理的字符串。
以命令行 schedule:test 为例,格式化后的命令行为 `/usr/local/php/bin/php` `artisan` schedule:test。若其运行周期设置为每分钟一次(* * * * *),则计算得到的 $key 值为 framework/schedule-768a42da74f005b3ac29ca0a88eb72d0ca2b84be。文件路径则是将 $key 进行 sha1 哈希计算后,每两个字符一组切分取前两项作为二级目录。结合配置文件中的默认存储路径 storage/framework/cache/data,最终文件路径形如 storage/framework/cache/data/eb/60/eb608bf555895f742e5bd57e186cbd97f9a6f432 ,文件中存储的内容则为类似 1642122685b:1 的时间戳格式数据。
⑵ 回调方法
关于 Event 回调的设置,调用 withoutOverlapping() 会为 Event 绑定两个回调函数:一个是 Event 执行完毕后的回调,用于释放互斥锁(即清理缓存文件);另一个是执行前的回调,用于判断互斥锁是否被占用(即检查缓存文件是否存在)。
无论 Event 以 Foreground 还是 Background 方式运行,执行完成后都会调用 callAfterCallbacks() 方法执行 afterCallbacks 中的回调列表,其中包括释放互斥锁的操作 $this->mutex->forget($this) 。区别在于,Foreground 模式是显式同步调用这些回调,而 Background 模式则依赖 schedule:finish 命令行来触发。所有在 \App\Console\Kernel 中注册的 Event 均通过 schedule:run 命令行调度。调度前,系统先校验当前时间是否满足各 Event 的运行周期要求,若满足则进入过滤条件判断,其中包括检查互斥锁状态。仅在互斥锁未被占用的情况下,Event 才会真正运行。
// namespace \Illuminate\Console\Scheduling\ScheduleRunCommand
public function handle(Schedule $schedule, Dispatcher $dispatcher)
{
$this->schedule = $schedule;
$this->dispatcher = $dispatcher;
foreach ($this->schedule->dueEvents($this->laravel) as $event) {
if (! $event->filtersPass($this->laravel)) {
$this->dispatcher->dispatch(new ScheduledTaskSkipped($event));
continue;
}
if ($event->onOneServer) {
$this->runSingleServerEvent($event);
} else {
$this->runEvent($event);
}
$this->eventsRan = true;
}
if (! $this->eventsRan) {
$this->info('No scheduled commands are ready to run.');
}
}
// namespace \Illuminate\Console\Scheduling\Schedule
public function dueEvents($app)
{
return collect($this->events)->filter->isDue($app);
}
// namespace \Illuminate\Console\Scheduling\Event
public function isDue($app)
{
/* ... ... */
return $this->expressionPasses() &&
$this->runsInEnvironment($app->environment());
}
protected function expressionPasses()
{
$date = Carbon::now();
/* ... ... */
return CronExpression::factory($this->expression)->isDue($date->toDateTimeString());
}
// namespace \Cron\CronExpression
public function isDue($currentTime = 'now', $timeZone = null)
{
/* ... ... */
try {
return $this->getNextRunDate($currentTime, 0, true)->getTimestamp() === $currentTime->getTimestamp();
} catch (Exception $e) {
return false;
}
}
public function getNextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false, $timeZone = null)
{
return $this->getRunDate($currentTime, $nth, false, $allowCurrentDate, $timeZone);
}
有时,开发者可能需要手动 kill 掉后台运行的命令行进程。然而,随后会发现这些被终止的进程在一段时间内无法按原定周期自动调度。原因在于,手动 kill 掉的命令行未能正常调用 schedule:finish 来清理缓存文件并释放互斥锁。这导致在预设的过期时间到达之前,互斥锁始终处于占用状态,新的 Event 实例无法再次启动。
到此这篇关于Laravel中schedule调度的运行机制的文章就介绍到这了,更多相关Laravel schedule调度内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!