Appearance
定时任务&控制台
定时任务一般应用于异步处理,应用解耦,定时执行等场景。
创建控制台类
DZ-SHOP的控制台类统一在console/controllers。
所有控制台类必须继承yii\console\Controller。例如:你需要一个需要定时执行的方法:
php
class HelloController extends yii\console\Controller
{
public function actionRun(): void
{
// 向控制台输出一段文字
Console::output('执行了run方法');
}
}
控制台命令
上面的方法可以通过控制台命令直接执行:
bash
php yii hello/run
控制台会输出文字:执行了run方法
你可以输入如下代码,获得所有系统支持的控制台命令:
bash
php yii
配置定时任务
需要定时执行的控制台方法统一在console/config/schedule.php中进行配置。比如我们要将上面的方法每分钟执行一次,只需要在schedule.php添加如下代码:
php
$schedule->command('hello/run')->everyMinute()->sendOutputTo($path . 'hello.log');
以下是配置定时任务的一些示例:
php
$schedule->command()->everyMinute() //每分钟执行一次
$schedule->command()->everyNMinutes(3) //每3分钟执行一次
$schedule->command()->everyFiveMinutes() //每5分钟执行一次
$schedule->command()->everyTenMinutes() //每10分钟执行一次
$schedule->command()->everyThirtyMinutes() //每30分钟执行一次
$schedule->command()->daily() //每天执行一次
$schedule->command()->dailyAt("13:00") //每天在13:00执行一次
$schedule->command()->twiceDaily() //每天执行2次
$schedule->command()->weekdays() //只在工作日执行,周一至周五
$schedule->command()->mondays() //只在周一执行
$schedule->command()->tuesdays() //只在周二执行
$schedule->command()->wednesdays() //只在周三执行
$schedule->command()->thursdays() //只在周四执行
$schedule->command()->fridays() //只在周五执行
$schedule->command()->saturdays() //只在周六执行
$schedule->command()->sundays() //只在周日执行
$schedule->command()->weekly() //每周执行一次
$schedule->command()->weeklyOn(3,"0:0") //每周三0点执行一次
$schedule->command()->monthly() //每月执行一次
$schedule->command()->yearly() //每年执行一次
如果上面的示例仍然不能满足要求,可以使用cron表达式:
php
$schedule->command()->cron('* * * * * *') //每分钟执行一次
$schedule->command()->cron('0 * * * * *') //每小时执行一次
你可以 点击这里 了解cron表达式(由于被墙的原因,你可能需要伸缩自如的梯子才能访问)。