# 命令行任务

你或许有一些业务并不是通过 Web 服务提供,比如运行一些后台任务之类的。Herosphp 提供一个 Command 工具来让你轻松实现你的这类需求。

先看一个例子:

# 简单例子

namespace app\controller;

use herosphp\annotation\Action;
use herosphp\annotation\Command;
use herosphp\core\BaseCommand;
use herosphp\core\Input;
use herosphp\utils\Logger;

#[Command(TestCmd::class)]
class TestCmd extends BaseCommand
{
    #[Action(uri: '/cli/test')]
    public function test(Input $input)
    {
        // 获取命令行参数
        $name = $input->get('name', 'herosphp');
        // 设置日志等级
        Logger::setLevel(Logger::INFO);
        Logger::info("Task $name start.");
    }
}

你会发现他跟控制器的结构很像,只是用到的注解不同而已。

你需要给你的控制器添加一个 @Command 注解,然后在对应的方法上添加 @Action 注解来为当前方法添加调用路由。

然后我们就可以使用下面的命令来执行这个任务了:

php client.php /cli/test

当然,你还可以传入参数,参数的格式是 name1=value1:name2=value2

php client.php /cli/test?name=herosphp:age=8

# 优雅退出

我们建议所有的命令行控制器都需继承 BaseCommand 这个类,我们在这个基础类中注册了一些进程中断信号(SIGHUP,SIGINT,SIGQUIT,SINTERM), 你可以在任务的运行过程捕获并处理这些信号,实现进程的优雅退出。

public function test(Input $input)
{
    // 获取命令行参数
    $name = $input->get('name', 'herosphp');
     while ($this->isRunning()) {
        // 如果你有循环处理的逻辑,写在这里,
        // 确保完成一轮循环才会退出,不会中途退出
    }

    Logger::info('任务退出');
}
上次更新: 10/27/2022, 11:18:25 AM