Laravel之任务调度
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Laravel之任务调度
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                一.基本簡介
任務調度定義在app/Console/Kernel.php 文件的schedule 方法中,該方法中已經包含了一個示例。你可以自
由地添加你需要的調度任務到Schedule 對象。
二.開啟調度
下面是你唯一需要添加到服務器的 Cron 條目:
* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1
該 Cron 將會每分鐘調用 Laravel 命令調度,然后,Laravel 評估你的調度任務并運行到期的任務。
三.定義調度
1.示例:
<?php
namespace AppConsole;
use IlluminateConsoleSchedulingSchedule;
use IlluminateFoundationConsoleKernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        CommandsInspire::class,
        CommandsSendEmails::class,
    ];
    /**
     * Define the application's command schedule.
     *
     * @param  IlluminateConsoleSchedulingSchedule  $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...
	});
總結
以上是生活随笔為你收集整理的Laravel之任务调度的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Amzon MWS API开发之 请求报
- 下一篇: matplotlib 28原则
