想在ThinkPHP中写一个定时任务,又不想这个任务是一个可以外网访问的地址怎么办?
ThinkPHP中提供了创建自定义指令的方法
参考官方示例:传送门
在命令台执行
php think make:command Hello hello
会生成一个 app\command\Hello 命令行指令类
在目标文件中打开,我们稍作修改
<?php
declare (strict_types=1);
/**
* for command test
* @author wolfcode
* @time 2020-06-04
*/
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
class Hello extends Command
{
protected function configure()
{
// 指令配置
$this->setName('hello')
->addArgument('name', Argument::OPTIONAL, "your name")
->addOption('city', null, Option::VALUE_REQUIRED, 'city name')
->setDescription('the hello command');
}
protected function execute(Input $input, Output $output)
{
$name = $input->getArgument('name');
$name = $name ?: 'wolfcode';
$city = '';
if ($input->hasOption('city')) {
$city = PHP_EOL . 'From ' . $input->getOption('city');
}
// 指令输出
$output->writeln("hello {$name}" . '!' . $city);
}
}
同时记得去注册下命令
在项目 config/console.php 中的'commands'加入
<?php
return [
'commands' => [
'hello' => \app\command\Hello::class,
]
];
官方给的写法如下(报错 Command "Hello" is not defined.)
<?php
return [
'commands' => [
'hello' => 'app\command\Hello',
]
];
配置完后就可以在命令台中测试了
php think hello
输出
hello wolfcode!
定时任务需要的代码写完了,现在加入到crontab中
首先先查找下当前php命令所在的文件夹
type -p grep php
例如在 /usr/local/bin/php,则 crontab -e 中可以这样写:(文件会越来越大)
* * * * * /usr/local/bin/php /path/yourapp/think hello>>/path/yourlog/hello.log 2>&1
如果你想把日志分成每天来单独记录,可以这样写:
* * * * * /usr/local/bin/php /path/yourapp/think hello>>/path/yourlog/hello_`date -d 'today' +\%Y-\%m-\%d`.log 2>&1
然后检查下 crontab -l 是否填写正常,最后去 /path/yourlog下 看看你的定时任务日志是否运行正常!