引言
定时器功能,顾名思义包含两个部分:
一是定时要执行的任务
二是设置定时执行的规则
这里用的是tp5.1的自定义指令处理任务、linux的crontab进行定时执行
一:tp5.1自定义指令处理任务
1:自定义指令:处理业务代码
<?php namespace app\common\timer; use think\Db; use think\console\Command; use think\console\Input; use think\console\input\Argument; use think\console\Output; class OrderTimer extends Command { public $typeMsg=[ 1=>'Deal Not Payed Order Num:', 2=>'Deal Done Order Num:', ]; protected function configure() { $this->setName('order') ->addArgument('type', Argument::OPTIONAL, "order type") ->setDescription('Auto Deal Order'); } protected function execute(Input $input, Output $output) { //1:验证参数 $type = trim($input->getArgument('type')); if (!in_array($type,[1,2])) { return $output->writeln("Please Input Right Type"); } //2:处理任务 switch ($type) { case 1: $res = $this->cancelNotPayedOrder();break; case 2: $res = $this->autoDoneOrder();break; } //3:对处理结果进行处理 if($res['status'] != 1){ //todo 预警:短信、钉钉、微信 return true; } $msg = $this->typeMsg[$type].$res['data']['count']; return $output->writeln(date("Y-m-d H:i:s").$msg) ; } // 清理未支付订单:订单超过15min未支付,将取消 public function cancelNotPayedOrder() { Db::startTrans(); try{ $orderArr = Db::name('order') ->where('status',1) ->where('create_time','lt',time()-15*60) ->field('id') ->select(); if(!empty($orderArr)){ $updateData = ['update_time'=>date('Y-m-d H:i:s'), 'status'=>9]; foreach($orderArr as $row){ $res = Db::name('order')->where('id', $row['id'])->update($updateData); if($res === false) exception('订单更新失败id:'.$row['id']); } } Db::commit(); return ['status'=>1, 'msg'=>'success', 'data'=>['count'=>count($orderArr)]]; }catch (\Exception $e){ Db::rollback(); return ['status'=>0, 'msg'=>$e->getMessage(), 'data'=>[]]; } } // 确认收货订单自动完成 public function autoDoneOrder() { //todo 业务根据逻辑写 } }
2:自定义指令添加到配置文件中
<?php return [ 'app\common\timer\OrderTimer', ];
3:测试自定义指令是否成功:php think order 1
4:控制器调用指令
<?php namespace app\index\controller; use think\Console; use think\Controller; class Index extends Controller { public function hello($type) { $output = Console::call('order ' . $type); return $output->fetch(); } }
二:crontab设置定时规则
# 定时器 * * * * * cd /www/wwwroot/app && /usr/bin/php think order 1 >> /tmp/order_timer.log 2>&1 * * * * * cd /www/wwwroot/app && /usr/bin/php think order 2 >> /tmp/order_timer.log 2>&1
本文为阿群原创文章,转载无需和我联系,但请注明来自阿群博客www.timedifferent.com