本文已在本人博客https://www.nsxsg.com/archives/186首发
ThinkPHP框架应用之定时任务
新建一个定时类
-
在
application/admin/command
目录下新建一个Test.php
文件 -
文件内容如下:
<?php
namespace app\admin\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
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 '定时任务成功啦~';
}
}
效果图如下:
修改 command.php
文件
文件位置
application/command.php
- 修改内容如下
return [
'app\admin\command\Test'
];
效果图:
查看ThinkPHP框架中定时是否添加成功
- 进入项目目录 (并非是根目录) ,使用命令查看
php think
效果图如下:
运行定时任务
php think test
效果如图:
在Linux中添加crontab
- 编辑crontab
# 编辑crontab
crontab -e
# 进入编辑模式后添加如下内容
* * * * * php /home/wwwroot/demo.com/think test # 每分钟执行一次计划任务
# 保存退出后重启crontab
/etc/init.d/crond restart
效果图如下: