使用定时计划?
使用定时计划来关闭,比如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();
在没有特殊配置的情况下,定时任务只能在一台服务器上执行,假如这个系统有非常多的未支付订单,这台定时任务服务器的负载可能就比较高,甚至出现单次任务的执行时间超过一分钟的情况,那么在你的这个代码的逻辑里某些订单就会被处理两次。