ThinkPHP5自定义命令行(服务器计划任务)

创建自定义命令行

第一步,配置command.php文件,目录在application/command.php

<?php
return [
    'app\home\command\Test',
];

第二步,建立命令类文件,新建application/home/command/Test.php

<?php
namespace app\home\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;

class Test extends Command
{
    protected function configure()
    {
        $this->setName('test')->setDescription('Here is the remark ');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln("TestCommand:");
    }
}

理解:configure()方法里面设置自定义的命令行命令,setName()方法是命令;setDescription()方法是该命令的描述。

execute()方法执行命令操作($this->其他的操作),命令操作在服务器上一般不可见,故需要存入日志文件,且无论该命令执行成功或失败。

注意:可使用trace()助手函数记录日志,第二个参数为错误级别。

try{
    Log::init([
        // 日志记录方式,内置 file socket 支持扩展
        'type'  => 'File',
        // 日志保存目录
        'path'  => ROOT_PATH.'/runtime/card_success/',
        // 日志记录级别
        'level' => ['error'],
    ]);
    
    // 执行代码
    echo 'success';
    trace("success",'error');
} catch(Exception $e){
    Log::init([
        // 日志记录方式,内置 file socket 支持扩展
        'type'  => 'File',
        // 日志保存目录
        'path'  => ROOT_PATH.'/runtime/card_error/',
        // 日志记录级别
        'level' => ['error'],
    ]);
    trace("执行错误:(".date("Y-m-d H:i:s").")".$e->getMessage(),'error');
}

服务器上定时命令行执行(以宝塔为例)

cd 根目录
php think test

猜你喜欢

转载自blog.csdn.net/qq_28137309/article/details/87880735