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


想在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,
  ]
];

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

<?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下 看看你的定時任務日志是否運行正常!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM