zl程序教程

您现在的位置是:首页 >  其它

当前栏目

Laravel之任务调度

laravel 任务调度
2023-09-27 14:19:41 时间

一.基本简介


任务调度定义在app/Console/Kernel.php 文件的schedule 方法中,该方法中已经包含了一个示例。你可以自
由地添加你需要的调度任务到Schedule 对象。

 

二.开启调度


下面是你唯一需要添加到服务器的 Cron 条目:

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

  

该 Cron 将会每分钟调用 Laravel 命令调度,然后,Laravel 评估你的调度任务并运行到期的任务。

 

三.定义调度

1.示例:

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Inspire::class,
        Commands\SendEmails::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('emails:send')->cron('1,30 * * * *');
        $schedule->call(function() {
                \Log::error('日志被调用了');
            })->everyMinute()
            ->before(function() {
                \Log::error('before');
            })
            ->after(function() {
                \Log::error('before');
            });
    }
}

  

command调用console命令
call调用一个闭包
exec调用系统命令

 

2.调度常用选项

 

这些方法可以和额外的约束一起联合起来创建一周特定时间运行的更加细粒度的调度,例如,要每周一调度一个命令:

$schedule->call(function () {
  // 每周星期一13:00运行一次...
})->weekly()->mondays()->at('13:00');

下面是额外的调度约束列表:

 

3.避免任务重叠
默认情况下,即使前一个任务仍然在运行调度任务也会运行,要避免这样的情况,可使用withoutOverlapping方法:

$schedule->command('emails:send')->withoutOverlapping();

  

4.任务输出

Laravel 调度器为处理调度任务输出提供了多个方便的方法。首先,使用sendOutputTo 方法,你可以发送输出到文件以便稍后检查:

$schedule->command('emails:send')
->daily()
->sendOutputTo($filePath);

或者发送到邮件

$schedule->command('foo')
->daily()
->sendOutputTo($filePath)
->emailOutputTo('foo@example.com');

  

注意: emailOutputTo 和sendOutputTo 方法只对command 方法有效,不支持call 方法。

 

5.任务钩子
使用before 和after 方法,你可以指定在调度任务完成之前和之后要执行的代码:

$schedule->command('emails:send')
	->daily()
	->before(function () {
		// Task is about to start...
	})
	->after(function () {
		// Task is complete...
	});