参考链接
https://blog.csdn.net/zy1281539626/article/details/79457849
https://blog.csdn.net/weixin_44680687/article/details/107666688
https://blog.csdn.net/asasasasaq/article/details/90693570
步骤
1. 新建 command 文件夹 / Test.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 文件,位置在 app/command.php
<?php
return ['app\admin\command\Test']; // 注意命名空间
3 运行 任务
打开命令行,运行 php think Test 命令
test 命令 使 execute 方法中运行的方法运行
Test 对应 $this->setName('**Test**')->setDescription("计划任务 Test"); 中的 setName值
4 linux 中执行
crontab -l 列出某个用户cron服务的详细内容;
crontab -e 编辑某个用户的cron服务:
(1)进入crontab -e之后按 i , 进行编辑
为了方便测试,可以先设置成每分钟执行一次 ,记录日志 在 /www/server/cron/dmp.log
*/1 * * * * php /www/wwwroot/dmp.com/think Test>> /www/server/cron/dmp.log 2>&1
其中 php /文件跟目录/think Test 注意目录一定要写绝对路径
(2)编写完之后按 Esc,退出编辑,按 “:wq” 保存
(3)之后输入 service crond restart 重启服务
ps
1 crontab 命令
service crond start //启动服务
service crond stop //关闭服务
service crond restart //重启服务
service crond reload //重新载入配置
service crond status //查看crontab服务状态
2 php think 运行任务
使用命令行进入项目根目录执行 php think
输入命令 php think Test
3 如提示 Command “Test” is not defined.
检查 $this->setName(‘Test’) 是否对应
检查 think 文件中
// 定义项目路径
define('APP_PATH', __DIR__ . '/app/'); 是否对应