Laravel 的计划任务

避免并发执行

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

这里需要注意,对于 call function 定义的计划任务,需要定义 name。否则会报错

production.ERROR: A scheduled event name is required to prevent overlapping. Use the 'name' method before 'withoutOverlapping'.

正确的做法是

$schedule->call(function () {
            DB::table('recent_users')->delete();
})->daily()
  ->name('project_delete_users')
  ->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

参考

转载于:https://www.cnblogs.com/sgm4231/p/10189694.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值