Redis 中文文档 Redis 中文文档
指南
redis.io (opens new window)
指南
redis.io (opens new window)
  • 关于
    • Redis 开源治理
    • Redis 发布周期
    • Redis 赞助商
  • 入门
  • 数据类型
  • Redis Stack
  • 命令
  • 手册

Yii2 Queue Extension


An extension for running tasks asynchronously via queues.

It supports queues based on DB, Redis, RabbitMQ, AMQP, Beanstalk, ActiveMQand Gearman.

Documentation is at docs/guide/README.md.

Build Status

Installation


The preferred way to install this extension is through composer :

  1. ``` sh
  2. php composer.phar require --prefer-dist yiisoft/yii2-queue

  3. ```

Basic Usage


Each task which is sent to queue should be defined as a separate class. For example, if you need to download and save a file the class may look like the following:

  1. ``` php
  2. class DownloadJob extends BaseObject implements \yii\queue\JobInterface
  3. {
  4.     public $url;
  5.     public $file;

  6.     public function execute($queue)
  7.     {
  8.         file_put_contents($this->file, file_get_contents($this->url));
  9.     }
  10. }
  11. ```

Here's how to send a task into the queue:

  1. ``` php
  2. Yii::$app->queue->push(new DownloadJob([
  3.     'url' => 'http://example.com/image.jpg',
  4.     'file' => '/tmp/image.jpg',
  5. ]));
  6. ```

To push a job into the queue that should run after 5 minutes:

  1. ``` php
  2. Yii::$app->queue->delay(5 * 60)->push(new DownloadJob([
  3.     'url' => 'http://example.com/image.jpg',
  4.     'file' => '/tmp/image.jpg',
  5. ]));
  6. ```

The exact way a task is executed depends on the used driver. Most drivers can be run using console commands, which the component automatically registers in your application.

This command obtains and executes tasks in a loop until the queue is empty:

  1. ``` shell
  2. yii queue/run
  3. ```

This command launches a daemon which infinitely queries the queue:

  1. ``` shell
  2. yii queue/listen
  3. ```

See the documentation for more details about driver specific console commands and their options.

The component also has the ability to track the status of a job which was pushed into queue.

  1. ``` php
  2. // Push a job into the queue and get a message ID.
  3. $id = Yii::$app->queue->push(new SomeJob());

  4. // Check whether the job is waiting for execution.
  5. Yii::$app->queue->isWaiting($id);

  6. // Check whether a worker got the job from the queue and executes it.
  7. Yii::$app->queue->isReserved($id);

  8. // Check whether a worker has executed the job.
  9. Yii::$app->queue->isDone($id);
  10. ```

For more details see the guide.
Last Updated: 2023-09-03 19:17:54