一 计划任务
1.1 安装contable
composer require hyperf/crontab
config/autload/processes.php 中添加
return [
Hyperf\Crontab\Process\CrontabDispatcherProcess::class,
];
1.2 配置计划任务
config/autoload/crontab.php
<?php
use Hyperf\Crontab\Crontab;
return [
// 是否开启定时任务
'enable' => true,
'crontab' => [
// Callback类型定时任务(默认)
(new Crontab())->setName('Foo')->setRule('* * * * *')->setCallback([App\Task\FooTask::class, 'execute'])->setMemo('这是一个示例的定时任务'),
],
];
1.3 编写Task
<?php
namespace App\Task;
class FooTask
{
public function execute()
{
file_put_contents("/tmp/cron.log", time(), FILE_APPEND);
//$this->logger->info(date('Y-m-d H:i:s', time()));
}
}
重启hyperf 后,计划任务将启动
二 command
2.1 安装代码
先安装
composer require hyperf/command
2.2 然后创建文件
#创建命令
php bin/hyperf.php gen:command DemoCommand
//或直接 复制代码
<?php
declare(strict_types=1);
namespace App\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
#[Command]
class DemoCommand extends HyperfCommand
{
public function __construct(protected ContainerInterface $container)
{
parent::__construct('demo:command');
}
public function configure()
{
parent::configure();
$this->setDescription('Hyperf Demo Command');
}
public function handle()
{
$this->line('Hello Hyperf!', 'info');
}
}
2.3 运行命令
php bin/hyperf.php demo:command
支持传参
public function handle()
{
$argument = $this->input->getArgument('name') ?? 'World';
$this->line('Hello ' . $argument, 'info');
}
protected function getArguments()
{
return [
['name', InputArgument::OPTIONAL, '这里是对这个参数的解释']
];
}