Hyperf 中 实现协程的并发执行脚本

业务背景:假设要一次性导出一年的数据,由于数据过大,脚本执行就会变得耗时过长,对于这种场景我们可以 业务数据 按月切割导出,并且月份跟月份之间处理代码耗时互不阻塞 !

Hyperf版本:2.2.0

<?php

namespace App\Command\Audit\Migrate;


use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Utils\Coroutine;
use Swoole\Coroutine\WaitGroup;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
/**
 * @Command
 */
#[Command]
class CollaborativePracticeScript extends HyperfCommand
{

    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('CollaborativePracticeScript');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('协程');
    }

    public function handle()
    {
        // 创建一个月份的数组,存储需要处理的月份数据
        $months = ['2021-01', '2021-02', '2021-03']; // 假设有多个月份需要处理

        // 创建一个 WaitGroup 实例,用于等待所有协程任务完成
        $waitGroup = new WaitGroup();

        // 使用协程来同时处理每个月的数据
        $results = [];
        foreach ($months as $month) {
            // 增加 WaitGroup 的计数器
            $waitGroup->add();

            // 创建一个协程任务
            Coroutine::create(function () use ($month, &$results, $waitGroup) {
                // 在这里编写处理 $month 数据的业务逻辑代码
                // 可以调用自定义的方法或服务
                // 例如:handleMonthData($month);

                // 这里只是一个示例,延时 1 秒钟模拟处理数据的耗时
                Coroutine::sleep(5);

                // 处理完成后,保存结果
                $results[] = $month . ' 数据处理完成';

                // 协程任务完成后,减少 WaitGroup 的计数器
                $waitGroup->done();
            });
        }

        // 等待所有协程任务完成
        $waitGroup->wait();

        // 打印每个任务的结果
        foreach ($results as $result) {
            echo $result . PHP_EOL;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值