目錄
runInBackground() 方法
withoutOverlapping() 方法
mutex 互斥鎖
⑴ 超时时间
⑵ 回调方法
首頁 php框架 Laravel 一文帶你了解Laravel schedule調度的運作機制

一文帶你了解Laravel schedule調度的運作機制

Feb 17, 2022 pm 07:26 PM
laravel

這篇文章帶大家聊聊Laravel 中 schedule 調度的運作機制,希望對大家有幫助!

一文帶你了解Laravel schedule調度的運作機制

  Laravel 的 console 命令列極大的方便了 PHP 定時任務的設定以及運行。以往透過 crontab 設定定時任務過程相對比較繁瑣,並且透過 crontab 設定的定時任務很難防止任務的交疊運作。

  所謂任務的交疊運行,是指由於定時任務運行時間較長,在crontab 設定的運行週期不盡合理的情況下,已經啟動的任務還沒有結束運行,而係統又啟動了新的任務去執行相同的操作。如果程式內部沒有處理好數據一致性的問題,那麼兩個任務同時操作同一份數據,很可能會導致嚴重的後果。

runInBackgroundwithoutOverlapping

  為了防止任務的交疊運行,Laravel 提供了withoutOverlapping()# 方法;為了能讓多任務在背景並行執行,Laravel 提供了runInBackground() 方法。

runInBackground() 方法

  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 的運作方式有兩種:ForegroundBackground 。二者的差異就在於多個 Event 是否可以並行執行。 Event 預設以Foreground 的方式運行,在這種運行方式下,多個Event 順序執行,後面的Event 需要等到前面的Event 運行完成後才能開始執行。

  但在實際應用中,我們往往是希望多個Event 可以並行執行,此時就需要呼叫EventrunInBackground() 方法將其運行方式設定為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 方式運行的Event ,其回呼方法是同步呼叫的,而採用Background 方式運行的Event ,其after 回呼則是透過schedule:finish 命令列來執行的。

withoutOverlapping() 方法

  在設定Event 的運行週期時,由於應用場景的不斷變化,很難避免某個特定的Event 在某個時間段內需要運行較長的時間才能完成,甚至在下一個運行週期開始時還沒有執行完成。如果不對這種情況進行處理,就會導致多個相同的Event 同時運行,而如果這些Event 當中涉及到對資料的操作並且程式中沒有處理好冪等問題,很可能會造成嚴重後果。

  為了避免上述的問題,Event 中提供了 withoutOverlapping() 方法,該方法透過將 Event##withoutOverlapping 屬性設定為TRUE ,在每次要執行Event 時會檢查目前是否存在正在執行的相同的Event ,如果存在,則不執行新的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 的超时时间。在向 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);
登入後複製

  设置了 withoutOverlappingEvent 在执行之前,首先会尝试获取 mutex 互斥锁,如果无法成功获取到锁,那么 Event 就不会执行。获取互斥锁的操作通过调用 mutexcreate() 方法完成。

  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() 的参数值为空,进而 eventMutexstore 属性值也为空。这样,在 eventMutexcreate() 方法中调用 store() 方法为其设置存储引擎时,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,说明获取互斥锁成功,之后会调用 FileStoreput() 方法写文件;否则,说明当前有相同的 Event 在运行,不会再运行新的 Event

  在调用 put() 方法写文件时,首先需要根据传参计算 eventMutex 的超时时间的秒数,之后再调用 FileStore 中的 put() 方法,将数据写入文件中。

// 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 通过调用 EventmutexName() 方法生成,其中需要用到 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\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 掉的命令行在一段时间内无法按照设置的运行周期自动调度,其原因就在于手动 kill 掉的命令行没有调用 schedule:finish 清理缓存文件,释放互斥锁。这就导致在设置的过期时间到达之前,互斥锁会一直被占用,新的 Event 不会再次运行。

【相关推荐:laravel视频教程

以上是一文帶你了解Laravel schedule調度的運作機制的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Laravel和CodeIgniter的最新版本對比 Laravel和CodeIgniter的最新版本對比 Jun 05, 2024 pm 05:29 PM

Laravel9和CodeIgniter4的最新版本提供了更新的功能和改進。 Laravel9採用MVC架構,提供資料庫遷移、驗證及模板引擎等功能。 CodeIgniter4採用HMVC架構,提供路由、ORM和快取。在性能方面,Laravel9的基於服務提供者設計模式和CodeIgniter4的輕量級框架使其具有出色的性能。在實際應用中,Laravel9適用於需要靈活性和強大功能的複雜項目,而CodeIgniter4適用於快速開發和小型應用程式。

Laravel 和 CodeIgniter 中資料處理能力的比較如何? Laravel 和 CodeIgniter 中資料處理能力的比較如何? Jun 01, 2024 pm 01:34 PM

比較Laravel和CodeIgniter的資料處理能力:ORM:Laravel使用EloquentORM,提供類別物件關係映射,而CodeIgniter使用ActiveRecord,將資料庫模型表示為PHP類別的子類別。查詢建構器:Laravel具有靈活的鍊式查詢API,而CodeIgniter的查詢建構器更簡單,基於陣列。資料驗證:Laravel提供了一個Validator類,支援自訂驗證規則,而CodeIgniter的驗證功能內建較少,需要手動編碼自訂規則。實戰案例:用戶註冊範例展示了Lar

Laravel 和 CodeIgniter 對於初學者來說哪一個比較友善? Laravel 和 CodeIgniter 對於初學者來說哪一個比較友善? Jun 05, 2024 pm 07:50 PM

對於初學者來說,CodeIgniter的學習曲線更平緩,功能較少,但涵蓋了基本需求。 Laravel提供了更廣泛的功能集,但學習曲線稍陡。在性能方面,Laravel和CodeIgniter都表現出色。 Laravel有更廣泛的文件和活躍的社群支持,而CodeIgniter更簡單、輕量級,具有強大的安全功能。在建立部落格應用程式的實戰案例中,Laravel的EloquentORM簡化了資料操作,而CodeIgniter需要更多的手動配置。

Laravel和CodeIgniter:哪種框架更適合大型專案? Laravel和CodeIgniter:哪種框架更適合大型專案? Jun 04, 2024 am 09:09 AM

在選擇大型專案框架時,Laravel和CodeIgniter各有優勢。 Laravel針對企業級應用程式而設計,提供模組化設計、相依性注入和強大的功能集。 CodeIgniter是一款輕量級框架,更適合小型到中型項目,強調速度和易用性。對於具有複雜需求和大量用戶的大型項目,Laravel的強大功能和可擴展性更為合適。而對於簡單專案或資源有限的情況下,CodeIgniter的輕量級和快速開發能力則較為理想。

Laravel - Artisan 指令 Laravel - Artisan 指令 Aug 27, 2024 am 10:51 AM

Laravel - Artisan 指令 - Laravel 5.7 提供了處理和測試新指令的新方法。它包括測試 artisan 命令的新功能,下面提到了演示?

Laravel和CodeIgniter:哪種框架比較適合小型專案? Laravel和CodeIgniter:哪種框架比較適合小型專案? Jun 04, 2024 pm 05:29 PM

對於小型項目,Laravel適用於大型項目,需要強大的功能和安全性。 CodeIgniter適用於非常小的項目,需要輕量級和易用性。

Laravel 和 CodeIgniter 的模板引擎哪一個比較好? Laravel 和 CodeIgniter 的模板引擎哪一個比較好? Jun 03, 2024 am 11:30 AM

比較了Laravel的Blade和CodeIgniter的Twig模板引擎,根據專案需求和個人偏好進行選擇:Blade基於MVC語法,鼓勵良好程式碼組織和模板繼承。 Twig是第三方函式庫,提供靈活語法、強大過濾器、擴充支援和安全沙箱。

Laravel - 分頁自訂 Laravel - 分頁自訂 Aug 27, 2024 am 10:51 AM

Laravel - 分頁自訂 - Laravel 包含分頁功能,可協助使用者或開發人員包含分頁功能。 Laravel 分頁器與查詢產生器和 Eloquent ORM 整合。自動分頁方法

See all articles