composer安装,具体文档请移步 [EasyTask] https://gitee.com/392223903/EasyTask
composer require easy-task/easy-task
创建文件
php think make:command Task task
会生成文件:tp\app\command\Task.php
<?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()
{
//设置名称为task
$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'));
// 配置任务,每隔20秒访问2次网站
$task = new \EasyTask\Task();
//是否常驻内存,false表示下面运行php think task start命令时不能退出小黑框,true的时候可退出小黑框
$task->setDaemon(true);
$task->setRunTimePath('./runtime/task/'); //缓存文件目录,手动创建定义
$task->addFunc(function () { //具体执行函数,方法一 addFunc()
$hour = date('H');
if ($hour != 15) { //每天下午3点执行定时任务
return;
}else{
//具体执行的业务逻辑
(new xxxController())->xxxMethod1();
}
}, 'checkPriceAndTime', 3600, 1); //checkPriceAndTime是task进程名,意为每3600秒(1小时)执行一次
//==========================================
//具体执行函数,方法二 addClass()
//$task->addClass(CrontabController::class, 'checkContractFeesPrice', 'oa_checkContractFeesPrice', 10, 1);
//$task->addClass(CrontabController::class, 'checkContractTime', 'oa_checkContractTime', 10, 1);
//根据命令执行
if ($action == 'start')
{
$task->start();
}
elseif ($action == 'status')
{
$task->status();
}
elseif ($action == 'stop')
{
$force = ($force == 'force'); //是否强制停止
$task->stop($force);
}
else
{
exit('Command is not exist');
}
}
}
配置tp\config\console.php文件
<?php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
// 指令定义
'commands' => [
'task' => 'app\command\Task', //task类所在位置
],
];
执行命令如下:
php think task start 启动命令 php think task status 查询命令 php think task stop 关闭命令 php think task stop force 强制关闭命令
