您好,欢迎访问一九零五行业门户网

一文带你了解Laravel schedule调度的运行机制

本篇文章带大家聊聊laravel 中 schedule 调度的运行机制,希望对大家有所帮助!
laravel 的 console 命令行极大的方便了 php 定时任务的设置以及运行。以往通过 crontab 配置定时任务过程相对比较繁琐,并且通过 crontab 设置的定时任务很难防止任务的交叠运行。
  所谓任务的交叠运行,是指由于定时任务运行时间较长,在 crontab 设置的运行周期不尽合理的情况下,已经启动的任务还没有结束运行,而系统又启动了新的任务去执行相同的操作。如果程序内部没有处理好数据一致性的问题,那么两个任务同时操作同一份数据,很可能会导致严重的后果。⒈ runinbackground 和 withoutoverlapping  为了防止任务的交叠运行,laravel 提供了 withoutoverlapping() 方法;为了能让多任务在后台并行执行,laravel 提供了 runinbackground() 方法。
⑴ runinbackground() 方法  console 命令行中的每一个命令都代表一个 event ,\app\console\kernel 中的 schedule() 方法的作用只是将这些命令行代表的 event 注册到 illuminate\console\scheduling\schedule 的属性 $events 中。
// namespace \illuminate\console\scheduling\schedulepublic 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 是否可以并行执行。event 默认以 foreground 的方式运行,在这种运行方式下,多个 event 顺序执行,后面的 event 需要等到前面的 event 运行完成之后才能开始执行。
  但在实际应用中,我们往往是希望多个 event 可以并行执行,此时就需要调用 event 的 runinbackground() 方法将其运行方式设置为 background 。
  laravel 框架对这两种运行方式的处理区别在于命令行的组装方式和回调方法的调用方式。
// namespace \illuminate\console\scheduling\eventprotected 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\commandbuilderpublic 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 方式运行的 event ,其回调方法是同步调用的,而采用 background 方式运行的 event ,其 after 回调则是通过 schedule:finish 命令行来执行的。
⑵ withoutoverlapping() 方法  在设置 event 的运行周期时,由于应用场景的不断变化,很难避免某个特定的 event 在某个时间段内需要运行较长的时间才能完成,甚至在下一个运行周期开始时还没有执行完成。如果不对这种情况进行处理,就会导致多个相同的 event 同时运行,而如果这些 event 当中涉及到对数据的操作并且程序中没有处理好幂等问题,很可能会造成严重后果。
  为了避免出现上述的问题,event 中提供了 withoutoverlapping() 方法,该方法通过将 event 的 withoutoverlapping 属性设置为 true ,在每次要执行 event 时会检查当前是否存在正在执行的相同的 event ,如果存在,则不执行新的 event 任务。
// namespace illuminate\console\scheduling\eventpublic 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 的超时时间。在向 illuminate\console\scheduling\schedule 的属性 $events 中注册 event 时,会调用 schedule 中的 exec() 方法,在该方法中会新建 event 对象,此时会向 event 的构造方法中传入一个 eventmutex ,这就是 event 对象中的属性 mutex ,超时时间就是为这个 mutex 设置的。而 schedule 中的 eventmutex 则是通过实例化 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\kernelprotected 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\schedulepublic function usecache($store){ if ($this->eventmutex instanceof cacheeventmutex) { $this->eventmutex->usestore($store); } /* ... ... */ return $this;}// namespace \illuminate\console\scheduling\cacheeventmutexpublic function create(event $event){ return $this->cache->store($this->store)->add( $event->mutexname(), true, $event->expiresat * 60 );}// namespace \illuminate\cache\cachemanagerpublic 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 属性值也为空。这样,在 eventmutex 的 create() 方法中调用 store() 方法为其设置存储引擎时,store() 方法的参数值也为空。
  当 store() 方法的传参为空时,会使用应用的默认存储引擎(如果不做任何修改,默认 cache 的存储引擎为 file)。之后会取得默认存储引擎的配置信息(引擎、存储路径、连接信息等),然后实例化存储引擎。最终,file 存储引擎实例化的是 \illuminate\cache\filestore 。
  在设置完存储引擎之后,紧接着会调用 add() 方法获取互斥锁。由于 store() 方法返回的是 \illuminate\contracts\cache\repository 类型的实例,所以最终调用的是 illuminate\cache\repository 中的 add() 方法。
// namespace \illuminate\cache\repositorypublic 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\filestorepublic 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 在运行,不会再运行新的 event 。
  在调用 put() 方法写文件时,首先需要根据传参计算 eventmutex 的超时时间的秒数,之后再调用 filestore 中的 put() 方法,将数据写入文件中。
// namespace \illuminate\cache\repositorypublic 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\filestorepublic 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\schedulepublic function mutexname(){ return 'framework'.directory_separator.'schedule-'.sha1($this->expression.$this->command);}
这里需要重点说明的是 $key 的生成方法以及文件路径的生成方法。$key 通过调用 event 的 mutexname() 方法生成,其中需要用到 event 的 $expression 和 $command 属性。其中 $command 为我们定义的命令行,在调用 $schedule->comand() 方法时传入,然后进行格式化,$expression 则为 event 的运行周期。
  以命令行 schedule:test 为例,格式化之后的命令行为 `/usr/local/php/bin/php` `artisan` schedule:test,如果该命令行设置的运行周期为每分钟一次,即 * * * * * ,则最终计算得到的 $key 的值为 framework/schedule-768a42da74f005b3ac29ca0a88eb72d0ca2b84be 。文件路径则是将 $key 的值再次进行 sha1 计算之后,以两个字符为一组切分成数组,然后取数组的前两项组成一个二级目录,而配置文件中 file 引擎的默认存储路径为 storage/framework/cache/data ,所以最终的文件路径为 storage/framework/cache/data/eb/60/eb608bf555895f742e5bd57e186cbd97f9a6f432 。而文件中存储的内容则为 1642122685b:1 。
⑵ 回调方法  再来说设置的 event 回调,调用 withoutoverlapping() 方法会为 event 设置两个回调:一个是 event 运行完成之后的回调,用于释放互斥锁,即清理缓存文件;另一个是在运行 event 之前判断互斥锁是否被占用,即缓存文件是否已经存在。
  无论 event 是以 foreground 的方式运行,还是以 background 的方式运行,在运行完成之后都会调用 callaftercallbacks() 方法执行 aftercallbacks 中的回调,其中就有一项回调用于释放互斥锁,删除缓存文件 $this->mutex->forget($this) 。区别就在于,以 foreground 方式运行的 event 是在运行完成之后显式的调用这些回调方法,而以 background 方式运行的 event 则需要借助 schedule:finish 来调用这些回调方法。
  所有在 \app\console\kernel 中注册 event,都是通过命令行 schedule:run 来调度的。在调度之前,首先会判断当前时间点是否满足各个 event 所配置的运行周期的要求。如果满足的话,接下来就是一些过滤条件的判断,这其中就包括判断互斥锁是否被占用。只有在互斥锁没有被占用的情况下,event 才可以运行。
// namespace \illuminate\console\scheduling\scheduleruncommandpublic 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\schedulepublic function dueevents($app){ return collect($this->events)->filter->isdue($app);}// namespace \illuminate\console\scheduling\eventpublic 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\cronexpressionpublic 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 掉的命令行在一段时间内无法按照设置的运行周期自动调度,其原因就在于手动 kill 掉的命令行没有调用 schedule:finish 清理缓存文件,释放互斥锁。这就导致在设置的过期时间到达之前,互斥锁会一直被占用,新的 event 不会再次运行。【相关推荐:laravel视频教程】
以上就是一文带你了解laravel schedule调度的运行机制的详细内容。
其它类似信息

推荐信息