前段时间在研究thinkphp5.0版本做自动任务的时候,碰到了棘手的问题–如何做自动化任务,因为程序开始就需要一直执行,查了很多资料,都说靠php原生的死循环来做不靠谱,时间误差也没法保证,所以后面采用thinkphp5的command工具和服务器的定时任务来做:
最简单的方法就算是直接在PHP代码里面实现 不过感觉不够高大上
<?php ignore_user_abort();//关掉浏览器,PHP脚本也可以继续执行. set_time_limit(3000);// 通过set_time_limit(0)可以让程序无限制的执行下去 $interval=5;// 每隔5s运行 //方法1--死循环 do{ echo'测试'.time().'<br/>'; sleep($interval);// 等待5s }while(true); //方法2---sleep 定时执行 require_once'./curlClass.php';//引入文件 $curl= new httpCurl();//实例化 $stime= $curl->getmicrotime(); for($i=0;$i<=10;$i++){ echo'测试'.time().'<br/>'; sleep($interval);// 等待5s } ob_flush(); flush(); $etime= $curl->getmicrotime(); echo'<hr>'; echoround(($etime-stime),4);//程序执行时间
1.新建command文件
在application/模块/新建一个command文件夹/Test.class.php
<?php namespace app\admin\command; use think\console\Command; use think\console\Input; use think\console\Output; class Test extends Command { protected function configure(){ $this->setName('Test')->setDescription("计划任务 Test"); } protected function execute(Input $input, Output $output){ $output->writeln('Date Crontab job start...'); /*** 这里写计划任务列表集 START ***/ $this->test(); /*** 这里写计划任务列表集 END ***/ $output->writeln('Date Crontab job end...'); } private function test(){ echo "test\r\n"; } }
2.配置command.php文件,位置在application/command.php
<?php return ['app\admin\command\Test'];
- 1
- 2
3.运行test命令
打开命令行,运行php think Test命令test命令execute方法中运行的方法就会运行
4.在应用根目录新建bat文件
task.bat文件
D:
cd D:\xampp\htdocs\autobet php think Test
- 1
- 2
- 3
5.将bat文件添加到服务器计划任务
这个根据window和Linux系统不一样,定时任务设置方法也不同,可以自行百度,我用的是本地的windows服务,详情看百度经验:Windows计划任务设置,定时执行指定脚本