前段时间在研究thinkphp5.0版本作自动任务的时候,碰到了棘手的问题–如何作自动化任务,由于程序开始就须要一直执行,查了不少资料,都说靠php原生的死循环来作不靠谱,时间偏差也无法保证,因此后面采用thinkphp5的command工具和服务器的定时任务来作:php
最简单的方法就算是直接在PHP代码里面实现 不过感受不够高大上html
<?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);//程序执行时间
在application/模块/新建一个command文件夹/Test.class.phpthinkphp
<?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"; } }
<?php return ['app\admin\command\Test'];
打开命令行,运行php think Test命令test命令execute方法中运行的方法就会运行windows
task.bat文件浏览器
D:
cd D:\xampp\htdocs\autobet php think Test
这个根据window和Linux系统不同,定时任务设置方法也不一样,能够自行百度,我用的是本地的windows服务,详情看百度经验:Windows计划任务设置,定时执行指定脚本服务器