alex-salt / yii2-tasks
Yii2 background task component
Installs: 1 001
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 1
Requires
- php: ^5.6 || ~7.0
- alex-salt/yii2-amqp: ^0.2
- mkraemer/react-pcntl: 2.0.*
- php-amqplib/php-amqplib: ^2.6
- react/event-loop: ^0.4 >=0.4.2
- yiisoft/yii2: ^2.0
Requires (Dev)
- phpunit/phpunit: ^5.7
This package is not auto-updated.
Last update: 2024-12-21 21:36:50 UTC
README
Component for running background tasks inside a react/event-loop
.
Install
composer require alex-salt/yii2-amqp
Usage
Configure application:
return [ 'components' => [ 'rmq' => [ 'class' => \alexsalt\amqp\Connection::class, 'host' => 'localhost', ], 'tasks' => [ 'class' => \alexsalt\tasks\TaskQueueComponent::class, 'rmq' => 'rmq', 'defaultQueue' => 'tasks', ], ], ];
Create a task
use alexsalt\tasks\TaskInterface; class MyTask implements TaskInterface { public $a; public $b = 1; public function run() { // your magic code } }
Send a task:
$task = new MyTask([ 'a' => 1, 'b' => 5 ]); Yii::$app->tasks->send($task);
A task worker:
use alexsalt\tasks\TaskWorker; class WorkerController extends \yii\console\Controller { public function actionMyTask() { $worker = new TaskWorker([ 'queue' => 'tasks', ]); $worker->start(); } }
Custom worker
use alexsalt\tasks\BaseMessage; use alexsalt\tasks\AbstractWorker; // declare message class with structure class MyMessage extends BaseMessage { public $a; public $b; } // declare worker with our handler class MyWorker extends AbstractWorker { /** * @param MyMessage $msg */ public function processMessage(BaseMessage $msg) { if ($msg->a - $msg->b) { return $this->ack($msg); } else if (!$msg->b) { Yii::error('dont like the message'); return $this->drop($msg); } else { return $this->nack($msg); } } } // create and send message $msg = new MyMessage([ 'a' => 1 ]); Yii::$app->rmq->sendToQueue($msg, 'my-queue'); // start worker that does stuff $worker = new MyWorker([ 'queue' => 'my-queue' ]); $worker->start();