任务调度–处理订单过期时间

启动调度器

使用这个调度器时,只需要把下面的 Cron 条目添加到你的服务器中。如果你不知道如何在服务器中添加 Cron 条目

首先执行

crontab -e

然后将这个添加到里面
/home/vagrant/code/showApi是绝对路径

* * * * * php /home/vagrant/code/showApi/artisan schedule:run >> /dev/null 2>&1


就是说,在Linux系统中该 Cron 会每分钟调用一次 Laravel 的命令行调度器。
在执行 schedule:run 命令时,Laravel 会根据你的调度执行预定的程序。

定义调度

可以在 AppConsoleKernel 类的 schedule 方法中定义所有的调度任务。

 //定时检测订单状态,超过十分钟未支付的,作废
        //在真实的项目中,不会这么做,真实的项目一般会使用长链接,订单过期,直接作废
        $schedule->call(function () {
            //查询状态为1并且时间不超过1分钟的订单
            $orders = Order::where('status', 1)
                ->where('created_at', ', date('Y-m-d H:i:s', time() - 600))
                ->with('orderDetails.goods')
                ->get();
            //循环订单,修改订单状态,还原商品库存
            try {
                DB::beginTransaction();//开启事务
                foreach ($orders as $order) {
                    $order->status = 5;//修改订单状态
                    $order->save();
                    //还原商品库存
                    foreach ($order->orderDetails as $details) {
                        $details->goods->increment('stock', $details->num);
                    }
                }
                DB::commit();//提交事务
            } catch (Exception $e) {
                Log::error($e);
            }
        })->everyMinute();

版权声明:
作者:linrux
链接:https://www.tot7.cn/technology/php/75.html
来源:阿信博客
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>