溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

laravel定時任務怎么使用

發(fā)布時間:2022-05-30 13:51:34 來源:億速云 閱讀:529 作者:iii 欄目:編程語言

這篇“l(fā)aravel定時任務怎么使用”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“l(fā)aravel定時任務怎么使用”文章吧。

應用場景

一個網(wǎng)站系統(tǒng)往往會有很多定時任務要執(zhí)行。例如推送訂閱消息,統(tǒng)計相關數(shù)據(jù)等,Linux一般采用crontab對定時任務進行設置和管理,但是隨著任務的增多,管理定時任務就比較麻煩,容易管理混亂。laravel 對此的解決方案是只設置一條定時任務,業(yè)務中所有的定時任務在這條定時任務進行處理和判斷,實現(xiàn)了在代碼層面對定時任務的管理。

基本用法

首先配置crontab:

* * * * * php artisan schedule:run >> /dev/null 2>&1

上面的意思是設置定時任務每分鐘執(zhí)行一次,具體的業(yè)務配置,放在了App\Console\Kernel 的 schedule 方法中:

class Kernel extends ConsoleKernel{
    Protected function schedule(Schedule $schedule)
    {
                //綜合數(shù)據(jù)統(tǒng)計
        $schedule->command('complex_data_log')
        ->everyMinute() //每分鐘執(zhí)行一次(除此之外還有,每五、十、十五、三十...,不同方法設置的默認時間不同)
        ->withoutOverlapping() //防止重復執(zhí)行
        ->onOneServer() //在單臺服務器上跑
        ->runInBackground() //任務后臺運行
        //->appendOutputTo('log_path')//日志輸出,默認追加
        ->sendOutputTo('log_path'); //日志輸出,默認覆蓋先前日志
    }}

原理解析:

基本原理:
schedule:run 這個指定是在vendor\illuminate\console\Scheduling\ScheduleRunCommand 類里面進行定義的,定義的形式和一般的定時任務相同:

/**
 * The console command name.
 *
 * @var string
 */protected $name = 'schedule:run';

在laravel 解析命令的時候,ScheduleRunCommand 這個類與 Kernel 類里面的 commands 數(shù)組進行了合并:

	/**
     * Get the commands to add to the application.
     *
     * @return array
     */
    protected function getCommands()
    {
        return array_merge($this->commands, [
            'Illuminate\Console\Scheduling\ScheduleRunCommand',
        ]);
    }

所以 php artisan schedule:run 命令就是框架內置的一個命令。
在命令啟動的時候,會默認找類中的handle 方法進行執(zhí)行:

/** vendor\illuminate\console\Command.php
 * Execute the console command.
 * 
 * @param  \Symfony\Component\Console\Input\InputInterface  $input
 * @param  \Symfony\Component\Console\Output\OutputInterface  $output
 * @return mixed
 */protected function execute(InputInterface $input, OutputInterface $output){
    return $this->laravel->call([$this, 'handle']);}

php artisan schedule:run 指令會每分鐘掃描Kernel::schedule里面注冊的所有指令,并判斷該指令是否已經(jīng)到達執(zhí)行周期,如果到達,就推入待執(zhí)行隊列:

    /**
     * Schedule the event to run every minute.
     * 代碼每分鐘執(zhí)行一次
     * @return $this
     */
    public function everyMinute()
    {
        return $this->spliceIntoPosition(1, '*');
    }
    
    /**
     * Splice the given value into the given position of the expression.
     * 拼接定時任務表達式
     * @param  int  $position
     * @param  string  $value
     * @return $this
     */
    protected function spliceIntoPosition($position, $value)
    {
        $segments = explode(' ', $this->expression);

        $segments[$position - 1] = $value;

        return $this->cron(implode(' ', $segments));
    }

ScheduleRunCommand::handle函數(shù):

/**
     * Execute the console command.
     * 
     * @return void
     */
    public function handle()
    {
        foreach ($this->schedule->dueEvents($this->laravel) as $event) {
            if (! $event->filtersPass($this->laravel)) {
                continue;
            }
            $this->runEvent($event);
        }
    }

避免任務重疊:
有時候單個定時任務執(zhí)行時間過長,到了下一個執(zhí)行時間后,上一次的執(zhí)行任務還沒有跑完,這個時候,我們可以采用withoutOverlapping()方法,避免任務重疊。在 withoutOverlapping方法中,給對應的任務加鎖(onOneServer 方法同理):

public function create(Event $event){
    return $this->cache->store($this->store)->add(
        $event->mutexName(), true, $event->expiresAt
    );}

只有拿到對應的任務鎖,才能執(zhí)行任務:

/**
     * Run the given event.
     * 運行任務
     * @param  \Illuminate\Contracts\Container\Container  $container
     * @return void
     */
    public function run(Container $container)
    {
        if ($this->withoutOverlapping &&
            ! $this->mutex->create($this)) {
            return;
        }
        
        //判斷是否是后臺運行
        $this->runInBackground
                    ? $this->runCommandInBackground($container)
                    : $this->runCommandInForeground($container);
    }

任務后臺運行:
由于定時任務是依次執(zhí)行的,上一個任務執(zhí)行時間過長,會影響下一個任務的執(zhí)行時間,所以我們可以采用runInBackground方法,將任務放到后臺執(zhí)行,有點類似于shell 中 & 的作用:

/**
     * Build the command for running the event in the background.
     * 構建定時任務后臺運行語句
     * @param  \Illuminate\Console\Scheduling\Event  $event
     * @return string
     */
    protected function buildBackgroundCommand(Event $event)
    {
        $output = ProcessUtils::escapeArgument($event->output);

        $redirect = $event->shouldAppendOutput ? ' >> ' : ' > ';

        $finished = Application::formatCommandString('schedule:finish').' "'.$event->mutexName().'"';

        return $this->ensureCorrectUser($event,
            '('.$event->command.$redirect.$output.' 2>&1 '.(windows_os() ? '&' : ';').' '.$finished.') > '
            .ProcessUtils::escapeArgument($event->getDefaultOutput()).' 2>&1 &'
        );
    }

其他用法:

除了上面的方法,我們還可以用laravel 的定時任務去調用Shell 命令:

$schedule->exec('node /home/forge/script.js')->daily();

也可以使用閉包進行調度:

$schedule->call(function () {
    DB::table('recent_users')->delete();})->daily();

以上就是關于“l(fā)aravel定時任務怎么使用”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI