myclabs/work

工作队列库,让您可以使用通用抽象来运行后台任务

0.4.0 2014-05-30 14:30 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:55:37 UTC


README

Build Status Coverage Status Scrutinizer Quality Score Total Downloads

MyCLabs\Work是一个工作队列库,允许您使用通用抽象在后台运行任务。

它的目的是与经典的工作队列解决方案(RabbitMQ、Beanstalkd等)兼容,同时提供高级抽象。

当前实现

  • InMemory:同步实现,任务直接执行(适用于测试或开发环境)
  • RabbitMQ
  • Beanstalkd

欢迎贡献并提交其他实现(Gearman等)。

扩展指南

工作原理

在您的代码中(例如HTTP请求),您可以在后台运行一个任务

$workDispatcher = new RabbitMQWorkDispatcher(/* parameters */);
$workDispatcher->run(new MyTask());

单独地,您设置一个持续在命令行上运行的工人(类似于守护进程)

$ php my-worker.php

这个工人只需调用

// my-worker.php
$worker = new RabbitMQWorker(/* parameters */);
// Will loop continuously and execute tasks
$worker->work();

定义任务

定义一个任务

class BigComputation implements MyCLabs\Work\Task\Task
{
    public $parameter1;
}

并定义执行任务的代码

class BigComputationExecutor implements MyCLabs\Work\TaskExecutor\TaskExecutor
{
    public function execute(Task $task)
    {
        if (! $task instanceof BigComputation) {
            throw new \Exception("Invalid task type provided");
        }
        // Perform the action (here we just multiply the parameter by 2)
        return $task->parameter1 * 2;
    }
}

执行任务并等待其结果

run($task)方法在后台运行任务。

如果您想等待该任务的结果,您必须使用实现了\MyCLabs\Work\Dispatcher\SynchronousWorkDispatcher接口的工作分配器。例如,RabbitMQ适配器实现了此接口。

该接口提供runAndWait方法

interface SynchronousWorkDispatcher extends WorkDispatcher
{
    /**
     * Run a task in background.
     *
     * You can use $wait to wait a given time for the task to complete.
     * If the task hasn't finished during this time, $timedout will be
     * called and this method will return.
     * If the task has finished, $completed will be called.
     *
     * @param Task     $task
     * @param int      $wait      Number of seconds to wait for the task to complete.
     *                            If 0, doesn't wait.
     * @param callable $completed Called (if $wait > 0) when the task has completed.
     * @param callable $timedout  Called (if $wait > 0) if we hit the timeout while
     *                            waiting.
     * @param callable $errored   Called (if $wait > 0) if the task errors. Takes 1
     *                            parameter which is the exception.
     *
     * @return void No results
     */
    public function runAndWait(
        Task $task,
        $wait = 0,
        callable $completed = null,
        callable $timedout = null,
        callable $errored = null
    );
}

阅读更多

文档中阅读更多。

贡献

您可以使用PHPUnit运行测试

$ composer install
$ vendor/bin/phpunit

一些功能测试需要外部程序,如RabbitMQ或Beanstalkd。出于实际原因,您可以使用Vagrant和包含的配置快速启动一个虚拟机。然后您可以在虚拟机中运行测试

$ vagrant up
$ vagrant ssh
$ cd /vagrant
$ composer install
$ vendor/bin/phpunit