Autotask.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace addons\shop\controller;
  3. use addons\shop\model\Order;
  4. use addons\shop\model\UserCoupon;
  5. use think\Controller;
  6. use think\Db;
  7. use addons\shop\model\OrderGoods;
  8. use addons\shop\model\OrderAction;
  9. /**
  10. * 定时任务接口
  11. *
  12. * 以Crontab方式每分钟定时执行,且只可以Cli方式运行
  13. * @internal
  14. */
  15. class Autotask extends Controller
  16. {
  17. /**
  18. * 初始化方法,最前且始终执行
  19. */
  20. public function _initialize()
  21. {
  22. // 只可以以cli方式执行
  23. if (!$this->request->isCli()) {
  24. $this->error('Autotask script only work at client!');
  25. }
  26. parent::_initialize();
  27. // 清除错误
  28. error_reporting(0);
  29. // 设置永不超时
  30. set_time_limit(0);
  31. }
  32. /**
  33. * 执行定时任务
  34. */
  35. public function index()
  36. {
  37. $time = time();
  38. try {
  39. $config = get_addon_config('shop');
  40. //确认收货时间
  41. $receive = $time - $config['auto_delivery_time'] * 24 * 60 * 60;
  42. //失效订单
  43. $order = Order::where(function ($query) use ($time) {
  44. $query->where('paystate', 0)->where('expiretime', '<=', $time)->where('orderstate', 0);
  45. })->whereOr(function ($query) use ($receive) {
  46. $query->where('shippingstate', 1)->where('paystate', 1)->where('shippingtime', '<=', $receive)->where('orderstate', 0);
  47. })->select();
  48. //超过设置订单状态为过期
  49. if ($order) {
  50. foreach ($order as $item) {
  51. // 启动事务
  52. Db::startTrans();
  53. try {
  54. //失效的
  55. if (!$item->paystate) {
  56. $item->save(['orderstate' => 2]);
  57. //库存恢复
  58. OrderGoods::setGoodsStocksInc($item->order_sn);
  59. //恢复优惠券
  60. UserCoupon::resetUserCoupon($item->user_coupon_id, $item->order_sn);
  61. } else { //待收货的
  62. $item->save(['shippingstate' => 2, 'receivetime' => time()]);
  63. OrderAction::push($item->order_sn, '系统', '订单确认收货成功');
  64. }
  65. // 提交事务
  66. Db::commit();
  67. } catch (\Exception $e) {
  68. // 回滚事务
  69. Db::rollback();
  70. continue;
  71. }
  72. }
  73. }
  74. } catch (\Exception $e) {
  75. echo $e->getMessage();
  76. }
  77. echo "done";
  78. }
  79. }