1.安装
安装比较简单用composer即可
composer require easy-task/easy-task
2.取消禁用依赖的函数
我使用linux主机,先把这些函数取消禁用
pcntl_fork,pcntl_wait,pcntl_signal,pcntl_alarm,pcntl_waitpid,pcntl_signal_dispatch
用windows主机需要开启com组件,执行命令时有提示的,按要求开启即可
3.使用php think make:command添加一个命令
php think make:command Task
config文件夹下console.php 文件添加指令
'commands' => [
"task" => "app\command\Task",
],
我添加了一个Task,生成的文件位于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()
{
// 指令配置
$this->setName('task')
//增加一个命令参数
->addArgument('action', Argument::OPTIONAL, "action")
->addArgument('force', Argument::OPTIONAL, "force")
->setDescription('task manager');
}
protected function execute(Input $input, Output $output)
{
//获取输入参数
$action = $force = '';
if ($input->getArgument('action'))
$action = trim($input->getArgument('action'));
if ($input->getArgument('force'))
$force = trim($input->getArgument('force'));
// 配置任务
$task = new \EasyTask\Task();
//设置常驻内存
$task->setDaemon(true);
$task->setRunTimePath('./runtime/task/');
//闭包函数类型定时任务
// $task->addFunc(function () use ($output) {
// //$output->writeln('hello');//每五秒执行一次
// Log::write(now());
// }, 'task', 5, 1);
$taskList = config('task');
//添加类的方法类型定时任务(同时支持静态方法)
foreach ($taskList as $one) {
$task->addClass('app\\task\\' . $one[0], 'handle', $one[0], $one[1], $one[2]);
}
// 根据命令执行
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');
}
}
}
4.在config下新建task.php配置文件,以后所有的计划任务都在这配置就好了
<?php
return [
['Order', 60, 1], //一分钟
['User', 3600, 1], //一小时
];
5.具体的计划任务编码
第4步中有两个任务,从第3步可以看出它们应该放在app\task命名空间下,而且一定要有一个公共的方法handle
<?php
declare(strict_types=1);
namespace app\task;
use think\facade\Db;
class Order
{
public function handle()
{
//业务逻辑
}
}
开启计划任务使用命令 php think task start 就行了,详细用法九猫科技
启动任务: php think task start
查询任务: php think task status
普通关闭: php think task stop
强制关闭: php think task stop force