转载了原作者的文章并结合自己的理解有所修改。
Ubuntu 下,命令行输入
crontab -e
打开了一个文件 然后在最后加入 这技术定时器,
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
然后我们重启了服务
service cron restart
下面是在laravel文件下的编写
app/Console/Kernel.php【上面的定时好了之后我们就测试了一下定时向日志中添加语句,并且是每分钟执行一次】
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
Log::info('ccc');
})->everyMinute();
}
示例,自动处理过期订单
Order.php
public static function handle_expired_order() {
$orders = self::where('status', self::STATUS_NEW)
->whereRaw("created_at < NOW() - INTERVAL 1 DAY")
->get();
foreach ($orders as $order) {
$order->status = self::STATUS_EXPIRED;
$order->save();
}
}
app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
Order::handle_expired_order();
})->hourly();
}
每小时执行
->hourly();
本地调试的时候,最好改成
->everyMinute();
方便查看效果。
当存在两个定时任务时需要 分开写
protected function schedule(Schedule $schedule){
第一个定时任务
$schedule->call(function () {
Log::info('ccc');
})
第二个定时任务
$schedule->call(function () {
Log::info('哎哎哎');
})
})->everyMinute();}
方便查看效果。