| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <?php
- /**
- * 订单超时自动取消定时任务
- */
- namespace app\crontab;
- use think\console\Command;
- use think\console\Input;
- use think\console\Output;
- use think\Db;
- use app\common\model\MemberCoinInfo;
- class PayTimeout extends Command
- {
- protected function configure()
- {
- $this->setName('PayTimeout')->setDescription('清理超时未支付订单');
- }
- protected function execute(Input $input, Output $output)
- {
- // 设置内存限制以防超大批次导致内存溢出
- ini_set('memory_limit', '1024M');
- $output->writeln(date('Y-m-d H:i:s') . " PayTimeout start\r\n");
- $this->handleTimeoutOrders($output);
- $output->writeln(date('Y-m-d H:i:s') . " PayTimeout end\r\n");
- }
- /**
- * 分批处理超时未支付的订单
- * @param Output $output
- */
- private function handleTimeoutOrders(Output $output)
- {
- $now = time();
- $limit = 500; // 单次查询和更新批次量
- $output->writeln("当前核对时间戳: {$now} = " . date('Y-m-d H:i:s'));
- while (true) {
- // 查询超时且需要处理的订单
- $list = Db::table('cy_paycpinfo')->alias('cpi')
- ->join('cy_pay cp', 'cpi.orderid = cp.orderid')
- ->where('cpi.pay_timeout', '>', 0)
- ->where('cpi.pay_timeout', '<', $now)
- ->where('cpi.payflag', 0)
- ->field("cpi.orderid, cp.userid")
- ->limit($limit)
- ->select();
- if (empty($list)) {
- $output->writeln("所有待处理超时订单清理完成。");
- break;
- }
- $count = count($list);
- $output->writeln("本批次发现 {$count} 条超时订单,准备执行取消...");
- // 取消订单:遍历每个订单,调用 releaseCoin 方法
- $successCount = 0;
- $failCount = 0;
- foreach ($list as $item) {
- $userid = $item['userid'];
- $orderid = $item['orderid'];
- $result = (new MemberCoinInfo())->releaseCoin($userid, $orderid, 3);
- if ($result) {
- $successCount++;
- $output->writeln("✔ 订单 {$orderid} 取消成功,用户ID: {$userid}");
- } else {
- $failCount++;
- $output->writeln("❌ 订单 {$orderid} 取消失败,用户ID: {$userid}");
- }
- }
- $output->writeln("本批次处理完成:成功 {$successCount} 条,失败 {$failCount} 条\r\n");
- // 若本次提取的数据不足限额,说明全部处理完毕,跳出循环
- if ($count < $limit) {
- break;
- }
- }
- }
- }
|