Merge pull request #212 from chrisboulton/beforeEnqueue

Add beforeEnqueue hook
This commit is contained in:
Chris Boulton 2015-02-04 10:56:54 -08:00
commit a8322cd4e7
6 changed files with 110 additions and 30 deletions

View file

@ -197,21 +197,28 @@ class Resque
* @param array $args Any optional arguments that should be passed when the job is executed.
* @param boolean $trackStatus Set to true to be able to monitor the status of a job.
*
* @return string
* @return string|boolean Job ID when the job was created, false if creation was cancelled due to beforeEnqueue
*/
public static function enqueue($queue, $class, $args = null, $trackStatus = false)
{
$result = Resque_Job::create($queue, $class, $args, $trackStatus);
if ($result) {
Resque_Event::trigger('afterEnqueue', array(
'class' => $class,
'args' => $args,
'queue' => $queue,
'id' => $result,
));
$id = Resque::generateJobId();
$hookParams = array(
'class' => $class,
'args' => $args,
'queue' => $queue,
'id' => $id,
);
try {
Resque_Event::trigger('beforeEnqueue', $hookParams);
}
catch(Resque_Job_DontCreate $e) {
return false;
}
return $result;
Resque_Job::create($queue, $class, $args, $trackStatus, $id);
Resque_Event::trigger('afterEnqueue', $hookParams);
return $id;
}
/**
@ -342,5 +349,15 @@ class Resque
$result = self::redis()->del('queue:' . $queue);
return ($result == 1) ? $counter : 0;
}
/*
* Generate an identifier to attach to a job for status tracking.
*
* @return string
*/
public static function generateJobId()
{
return md5(uniqid('', true));
}
}

View file

@ -47,17 +47,21 @@ class Resque_Job
* @param string $class The name of the class that contains the code to execute the job.
* @param array $args Any optional arguments that should be passed when the job is executed.
* @param boolean $monitor Set to true to be able to monitor the status of a job.
* @param string $id Unique identifier for tracking the job. Generated if not supplied.
*
* @return string
*/
public static function create($queue, $class, $args = null, $monitor = false)
public static function create($queue, $class, $args = null, $monitor = false, $id = null)
{
if (is_null($id)) {
$id = Resque::generateJobId();
}
if($args !== null && !is_array($args)) {
throw new InvalidArgumentException(
'Supplied $args must be an array.'
);
}
$id = md5(uniqid('', true));
Resque::push($queue, array(
'class' => $class,
'args' => array($args),

View file

@ -0,0 +1,12 @@
<?php
/**
* Exception to be thrown if while enqueuing a job it should not be created.
*
* @package Resque/Job
* @author Chris Boulton <chris@bigcommerce.com>
* @license http://www.opensource.org/licenses/mit-license.php
*/
class Resque_Job_DontCreate extends Exception
{
}