TP5的命令行执行取消订单
商城项目会有15分钟自动取消未支付的订单操作,最初使用的时定时任务,一分钟或者半分钟执行一次,
后来遇到一个技术大佬,不让使用定时任务进行操作,一来任务查询则塞的时候,默认php链接为30秒,
一旦超过之后就会报错,无法执行,让我们使用tp5框架的command命令,在linux中执行,使用到了死循
环和sleep操作,只适合访问量不大的操作
第一步
先在controller同级目录下建command文件夹,创建文件,并且编写对应的操作代码
<?php
namespace app\api\command;
use app\admin\model\Order;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class Esc extends Command
{
public function configure()
{
$this->setName('escOrder')->setDescription('15m取消订单');
}
public function execute(Input $input, Output $output)
{
while (true) {
$orderAppModel = new Order();
$where['status'] = 1;
$where['project_id'] = 3;
try{
//可以在使用MySQL的时间查询函数进行查询出对应数据
$orderList = $orderAppModel->where($where)->limit(0,100)->select();
if($orderList['rows']){
foreach ($orderList['rows'] as $key => $order){
if(time() - strtotime($order['create_time']) > 60*15){
$wheres['id'] = $order['id'];
$orderAppModel->where($wheres)->update(['status' => 6,'esc_time' => time(),]);
}
}
}else{
sleep(3);
}
}catch (Exception $e) {
$output->error($e->getMessage());
}
}
}
}
第二步 :
使用php think生成命令行 并 php think Esc 执行文件
也可以使用nohup php think Esc在linux下后台不挂断地运行,退出终端不会影响程序的运行