前段时间在研究thinkphp5.0版本做自动任务的时候,碰到了棘手的问题–如何做自动化任务,因为程序开始就需要一直执行,查了很多资料,都说靠php原生的死循环来做不靠谱,时间误差也没法保证,所以后面采用thinkphp5的command工具和服务器的定时任务来做:
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"; } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
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计划任务设置,定时执行指定脚本