使用定时计划?

使用定时计划来关闭,比如30分钟之前未支付的订单是否可以
跟队列比较是否有什么不妥之处?

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Order;
use Carbon\Carbon;

class CloseOrders extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'close:orders';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '关闭未支付的订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //获取某个时间前未支付的订单
        $orders = Order::query()->whereNull('paid_at')
                                      ->where('closed', false)
                                      ->where('created_at', '<=', Carbon::now()->subMinutes(config('app.order_ttl')))
                                      ->get();
        \DB::transaction(function () use ($orders) {
            foreach ($orders as $order) {
                // 将订单的 closed 字段标记为 true,即关闭订单
                $order->update(['closed' => true]);
                foreach ($order->items as $item) {
                    //归还库存
                    $item->productSku->addStock($item->amount);
                }
            }
        });
    }
}
$schedule->command('close:orders')->everyMinute();
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
leo
最佳答案

在没有特殊配置的情况下,定时任务只能在一台服务器上执行,假如这个系统有非常多的未支付订单,这台定时任务服务器的负载可能就比较高,甚至出现单次任务的执行时间超过一分钟的情况,那么在你的这个代码的逻辑里某些订单就会被处理两次。

5年前 评论
讨论数量: 2
leo

在没有特殊配置的情况下,定时任务只能在一台服务器上执行,假如这个系统有非常多的未支付订单,这台定时任务服务器的负载可能就比较高,甚至出现单次任务的执行时间超过一分钟的情况,那么在你的这个代码的逻辑里某些订单就会被处理两次。

5年前 评论
leo

在没有特殊配置的情况下,定时任务只能在一台服务器上执行,假如这个系统有非常多的未支付订单,这台定时任务服务器的负载可能就比较高,甚至出现单次任务的执行时间超过一分钟的情况,那么在你的这个代码的逻辑里某些订单就会被处理两次。

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!