1. 程式人生 > 實用技巧 >ThinkPHP6 利用crontab+think make:command執行定時任務 tp6預設不可以用命令列訪問控制器

ThinkPHP6 利用crontab+think make:command執行定時任務 tp6預設不可以用命令列訪問控制器

想在ThinkPHP中寫一個定時任務,又不想這個任務是一個可以外網訪問的地址怎麼辦?

ThinkPHP中提供了建立自定義指令的方法

參考官方示例:傳送門

在命令臺下

phpthinkmake:commandHellohello

會生成一個 app\command\Hello 命令列指令類

在目標檔案中開啟,我們稍作修改

<?php
declare(strict_types=1);
/**
*forcommandtest
*@authorwolfcode
*@time2020-06-04
*/

namespaceapp\command;

usethink\console\Command;
usethink\console\Input;
usethink\console\input\Argument;
usethink\console\input\Option;
usethink\console\Output;

classHelloextendsCommand
{
protectedfunctionconfigure()
{
//指令配置
$this->setName('hello')
->addArgument('name',Argument::OPTIONAL,"yourname")
->addOption('city',null,Option::VALUE_REQUIRED,'cityname')
->setDescription('thehellocommand');
}

protectedfunctionexecute(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,
]
];

官方的寫法是下面這樣的(但是我按照這樣寫會報錯)

<?php
return[
'commands'=>[
'hello'=>'app\command\Hello',
]
];

配置完後就可以在命令臺中測試了

phpthinkhello

輸出

hellowolfcode!

定時任務需要的程式碼寫完了,現在加入到crontab中

首先先查詢下當前php命令所在的資料夾

type-pgrepphp

例如在 /usr/local/bin/php,則 crontab -e 中可以這樣寫:(檔案會越來越大)

*****/usr/local/bin/php/path/yourapp/thinkhello>>/path/yourlog/hello.log2>&1

如果你想把日誌分成每天來單獨記錄,可以這樣寫:

*****/usr/local/bin/php/path/yourapp/thinkhello>>/path/yourlog/hello_`date-d'today'+\%Y-\%m-\%d`.log2>&1

然後檢查下 crontab -l 是否填寫正常,最後去/path/yourlog下 看看你的定時任務日誌是否執行正常!