Table Of ContentsPrevious topicNext topic |
Queueing¶Perform activities like process a video, resize images or send emails aren’t suitable to be executed online or in real time because it may slow the loading time of pages, impacting the user experience. The best solution here is implementing background jobs. A web application must put the job into a queue and wait that it will be processed. While you can find more sophisticated PHP extensions to address queueing in your applications like RabbitMQ; Phalcon provides a client for Beanstalk, a job queueing backend inspired by Memcache. It’s simple, lightweight, and completely specialized on job queueing. Putting Jobs into the Queue¶After connecting to Bens can insert as many jobs as required. The developer can define the message structure according to the needs of the application: <?php
//Connect to the queue
$queue = new Phalcon\Queue\Beanstalk(array(
'host' => '192.168.0.21'
));
//Insert the job in the queue
$queue->put(array('processVideo' => 4871));
Available connection options are:
In the above example we stored a message which will allow a background job to process a video. The message is stored in the queue immediately and does not have a certain time to life. Additional options as time to run, priority and delay could be passed as second parameter: <?php
//Insert the job in the queue with options
$queue->put(
array('processVideo' => 4871),
array('priority' => 250, 'delay' => 10, 'ttr' => 3600)
);
The following options are available:
Every job put into the queue returns a “job id” the developer can use to track the status of the job: <?php
$jobId = $queue->put(array('processVideo' => 4871));
Retrieving Messages¶Once a job is placed into the queue, those messages can be consumed by a background job which have enough time to complete the task: <?php
while (($job = $queue->peekReady()) !== false) {
$message = $job->getBody();
var_dump($message);
$job->delete();
}
Jobs must be removed from the queue to avoid double processing. If multiple background jobs workers are implemented, jobs must be “reserved” so other workers don’t re-process them while other workers have them reserved: <?php
while ($queue->peekReady() !== false) {
$job = $queue->reserve();
$message = $job->getBody();
var_dump($message);
$job->delete();
}
Our client implement a basic set of the features provided by Beanstalkd but enough to allow you to build applications implementing queues. |