laravel crontab

发布时间:2017-12-28 18:46:00 阅读:1104次

http://www.sunzhongwei.com/laravel-schedule-a-task-that-is-much-more-convenient-than-linux-system-crontab

http://blog.csdn.net/wangjinbao5566/article/details/72881382

https://www.cnblogs.com/xj76149095/p/6221639.html

例如,我想加一个新功能,24小时内未支付的订单自动变更状态。以前都是通过系统 crontab 定时执行,但是缺点很明显。每次都需要手动配置 crontab,不方便在项目中集中管理。

看了一下 Laravel 的 scheduling 确实方便不少。

避免并发执行

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

编辑任务

app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
        $schedule->call(function () {
            DB::table('recent_users')->delete();
        })->daily();
}

注意这里使用了匿名函数。

具体实现函数,可以在其他模块中实现,然后在匿名函数中调用。

示例,自动处理过期订单

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();

方便查看效果。

最后不要忘了添加系统 crontab

Ubuntu 下,命令行输入

crontab -e

然后在最后加入

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

参考

测试环境

Laravel 5.5

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询
上一篇:群晖安装
下一篇:群晖 samba rsync

转载请注明:laravel crontab 出自老鄢博客 | 欢迎分享