1.Composer安装
composer require easy-task/easy-task
2. 创建类
php think make:command Task task
<?php
declare (strict_types=1);
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 Task extends Command
{
protected function configure()
{
$this->setName('task')
->addArgument('action', Argument::OPTIONAL, "action", '')
->addArgument('force', Argument::OPTIONAL, "force", '');
}
protected function execute(Input $input, Output $output)
{
$action = trim($input->getArgument('action'));
$force = trim($input->getArgument('force'));
$task = new \EasyTask\Task();
$task->setRunTimePath('./runtime/');
$task->addFunc(function () {
file_put_contents('task_log.txt',json_encode(['date'=>date('Y-m-d H:i:s')]).PHP_EOL,FILE_APPEND);
}, 'request', 20, 1);;
if ($action == 'start')
{
$task->setDaemon(true);
$task->start();
}
elseif ($action == 'status')
{
$task->status();
}
elseif ($action == 'stop')
{
$force = ($force == 'force');
$task->stop($force);
}
else
{
exit('Command is not exist');
}
}
}
3.配置config\console.php文件
<?php
return [
'commands' => [
'task' => 'app\command\Task',
],
];
php think task start 启动命令
php think task status 查询命令
php think task stop 关闭命令
php think task stop force 强制关闭命令