laravel 8 任务调度和延时分发
根据我平常的简单使用,总结一下 laravel 8 的任务调度和延时分发的简单使用
首先:
任务调度:定时,定期执行任务
应用场景:定时数据库备份
延时分发:延时执行任务
应用场景:订单30分钟未支付取消订单
任务调度
在 Console 里生成调用文件
php artisan make:command TestOne
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class TestOne extends Command
{
/**
* The name and signature of the console command.
* 此处是任务调度的名称
* @var string
*/
protected $signature = 'TestOne';
/**
* The console command description.
* 对定时任务的描述
* @var string
*/
protected $description = '测试1';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
* 任务的逻辑代码
* @return int
*/
public function handle()
{
Log::info('TestOne 定时任务执行');
}
}
在 Kernel.php 里定义调度任务
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
//每分钟执行
$schedule->command('TestOne')->everyMinute();
}
查看所有任务
php artisan schedule:list
执行任务
php artisan schedule:work
延时分发
使用 redis 队列做任务分发,每次的任务会以有序集合的方式存储在redis中,根据设定的延时时间,进行消费,分发,即执行
直接修改.env配置文件
QUEUE_CONNECTION=redis
生成任务类
php artisan make:job FirstJob
调用任务类
dispatch(new FirstJob($arr, 30));//延时30秒执行
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class FirstJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $data;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($arr,$delay)
{
$this->data = $arr;
$this->delay($delay);
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$name=$this->data['name'];
Log::info('现在延时分发执行'.$name);
}
}
执行
php artisan queue:work
本作品采用《CC 协议》,转载必须注明作者和本文链接
任务调度:
延时分发队列任务: