/** * Enqueue a job for execution at a given timestamp. * * Identical to Resque::enqueue, however the first argument is a timestamp * (either UNIX timestamp in integer format or an instance of the DateTime * class in PHP). * * @param DateTime|int $at Instance of PHP DateTime object or int of UNIX timestamp. * @param string $queue The name of the queue to place the job in. * @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. */ public static function enqueueAt($at, $queue, $class, $args = array()) { self::validateJob($class, $queue); $job = self::jobToHash($queue, $class, $args); self::delayedPush($at, $job); Resque_Event::trigger('afterRepeatSchedule', array('at' => $at, 'queue' => $queue, 'class' => $class, 'args' => $args)); }
public function testAfterEnqueueEventCallbackFires() { $callback = 'afterEnqueueEventCallback'; $event = 'afterEnqueue'; Resque_Event::listen($event, array($this, $callback)); Resque::enqueue('jobs', 'Test_Job', array('somevar')); $this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback . ') was not called'); }
/** * Mark the current job as having failed. * * @param $exception */ public function fail($exception) { Resque_Event::trigger('onFailure', array('exception' => $exception, 'job' => $this)); $this->updateStatus(Resque_Job_Status::STATUS_FAILED); Resque_Failure::create($this->payload, $exception, $this->worker, $this->queue); Resque_Stat::incr('failed'); Resque_Stat::incr('failed:' . $this->worker); }
/** * Schedule all of the delayed jobs for a given timestamp. * * Searches for all items for a given timestamp, pulls them off the list of * delayed jobs and pushes them across to Resque. * * @param DateTime|int $timestamp Search for any items up to this timestamp to schedule. */ public function enqueueDelayedItemsForTimestamp($timestamp) { $item = null; while ($item = ResqueRepeater::nextItemForTimestamp($timestamp)) { $this->log('queueing ' . $item['class'] . ' in ' . $item['queue'] . ' [delayed]'); Resque_Event::trigger('beforeDelayedEnqueue', array('queue' => $item['queue'], 'class' => $item['class'], 'args' => $item['args'])); $payload = array_merge(array($item['queue'], $item['class']), $item['args']); call_user_func_array('Resque::enqueue', $payload); } }
/** * Register php-resque-statsd in php-resque. * * Register all callbacks in php-resque for when a job is run. This is * automatically called at the bottom of this script if the appropriate * Resque classes are loaded. */ public static function register() { // Core php-resque events Resque_Event::listen('afterEnqueue', 'ResqueStatsd::afterEnqueue'); Resque_Event::listen('beforeFork', 'ResqueStatsd::beforeFork'); Resque_Event::listen('afterPerform', 'ResqueStatsd::afterPerform'); Resque_Event::listen('onFailure', 'ResqueStatsd::onFailure'); // Add support for php-resque-scheduler Resque_Event::listen('afterSchedule', 'ResqueStatsd::afterSchedule'); }
/** * Schedule all of the delayed jobs for a given timestamp. * * Searches for all items for a given timestamp, pulls them off the list of * delayed jobs and pushes them across to Resque. * * @param DateTime|int $timestamp Search for any items up to this timestamp to schedule. */ public function enqueueDelayedItemsForTimestamp($timestamp) { $item = null; while ($item = ResqueScheduler::nextItemForTimestamp($timestamp)) { $this->log(array('message' => 'Moving scheduled job ' . strtoupper($item['class']) . ' to ' . strtoupper($item['queue']), 'data' => array('type' => 'movescheduled', 'args' => array('timestamp' => (int) $timestamp, 'class' => $item['class'], 'queue' => $item['queue'], 'job_id' => $item['args'][0]['id'], 'wait' => round(microtime(true) - (isset($item['s_time']) ? $item['s_time'] : 0), 3), 's_wait' => $timestamp - floor(isset($item['s_time']) ? $item['s_time'] : 0)))), self::LOG_TYPE_INFO); \Resque_Event::trigger('beforeDelayedEnqueue', array('queue' => $item['queue'], 'class' => $item['class'], 'args' => $item['args'])); $payload = array_merge(array($item['queue'], $item['class']), $item['args'], array($item['track'])); call_user_func_array('\\Resque::enqueue', $payload); } }
public function testStopListeningRemovesListener() { $callback = 'beforePerformEventCallback'; $event = 'beforePerform'; Resque_Event::listen($event, array($this, $callback)); Resque_Event::stopListening($event, array($this, $callback)); $job = $this->getEventTestJob(); $this->worker->perform($job); $this->worker->work(0); $this->assertNotContains($callback, $this->callbacksHit, $event . ' callback (' . $callback . ') was called though Resque_Event::stopListening was called'); }
public function perform() { try { $closure = $this->getClosure(); Resque_Event::trigger('beforePerform', $this); Resque_Job_Closure::invokeSerializableClosure($closure, $this, $this->getArguments()); Resque_Event::trigger('afterPerform', $this); } catch (Resque_Job_DontPerform $e) { return false; } return true; }
/** * Enqueue a job for execution at a given timestamp. * * Identical to Resque::enqueue, however the first argument is a timestamp * (either UNIX timestamp in integer format or an instance of the DateTime * class in PHP). * * @param DateTime|int $at Instance of PHP DateTime object or int of UNIX timestamp. * @param string $queue The name of the queue to place the job in. * @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 $trackStatus Set to true to be able to monitor the status of a job. * @return string Job ID */ public static function enqueueAt($at, $queue, $class, $args = array(), $trackStatus = false) { self::validateJob($class, $queue); $args['id'] = md5(uniqid('', true)); $args['s_time'] = time(); $job = self::jobToHash($queue, $class, $args, $trackStatus); self::delayedPush($at, $job); if ($trackStatus) { \Resque_Job_Status::create($args['id'], Job\Status::STATUS_SCHEDULED); } \Resque_Event::trigger('afterSchedule', array('at' => $at, 'queue' => $queue, 'class' => $class, 'args' => $args)); return $args['id']; }
/** * Initialize the class and set its properties. * * @since 1.0.0 * @param string $plugin_name The name of this plugin. * @param string $version The version of this plugin. */ public function __construct($plugin_name, $version) { $this->plugin_name = $plugin_name; $this->version = $version; $this->redis = new Predis\Client(['scheme' => 'tcp', 'host' => REDIS_HOST, 'port' => REDIS_PORT, 'password' => REDIS_PASSWORD]); $this->blog_id = get_current_blog_id(); if (function_exists('get_blog_details')) { $details = get_blog_details($this->blog_id, 'domain', false); $domain = $details->domain; $sub_domain = explode(".", $domain)[0]; $this->sub_domain = $sub_domain; } Resque::setBackend(REDIS_HOST . ":" . REDIS_PORT, REDIS_DB); Resque_Event::listen('afterPerform', array('RooftopJob', 'afterPerform')); }
public function perform() { try { Resque_Event::trigger('beforePerform', $this); $instance = $this->getInstance(); if (method_exists($instance, 'setUp')) { $instance->setUp(); } $method = $this->method; $instance->{$method}($this, $this->getArguments()); if (method_exists($instance, 'tearDown')) { $instance->tearDown(); } Resque_Event::trigger('afterPerform', $this); } catch (Resque_Job_DontPerform $e) { return false; } return true; }
private function perform($job) { // $startTime = microtime(true); try { if (!$job instanceof \Randr\Job) { throw new \Exception('Job is not a class'); } \Resque_Event::trigger('afterFork', $job); $rc = $job->perform(); //$this->log(array('message' => 'done ID:' . $job->payload['id'], 'data' => array('type' => 'done', 'job_id' => $job->payload['id'], 'time' => round(microtime(true) - $startTime, 3) * 1000)), self::LOG_TYPE_INFO) } catch (Exception $e) { /*$this->log([ 'message' => $job . ' failed: ' . $e->getMessage(), 'data' => [ 'type' => 'fail', 'log' => $e->getMessage(), 'job_id' => $job->payload['id'], 'time' => round(microtime(true) - $startTime, 3) * 1000 ]], Resque_Worker::LOG_TYPE_ERROR ); */ if ($job instanceof \Randr\Job) { $job->fail($e); } print "ERROR: " . $e->getMessage() . "\n"; } $this->emit('finish', [$rc]); $job->updateStatus(\Resque_Job_Status::STATUS_COMPLETE); if ($this->ttl > 0) { $this->ttl--; } if ($this->ttl == 0) { print "TIME TO DIE for " . getmypid() . "\n"; exit(0); } }
/** * Create a new job and save it to the specified queue. * * @param string $queue The name of the queue to place the job in. * @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 $trackStatus Set to true to be able to monitor the status of a job. * * @return string */ 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)); } return $result; }
protected function enqueueFromConfig($config) { if (isset($config['cron'])) { //ResqueScheduler::removeDelayed($config['args']['queue'], $config['class'], $config['args']); $this->logger->log(Psr\Log\LogLevel::NOTICE, 'queueing {class} in {queue} Scheduled {schedule_at}', array('class' => $config['class'], 'queue' => $config['args']['queue'], 'schedule_at' => $config['schedule_at'])); ResqueScheduler::enqueueAt($config['schedule_at'], $config['args']['queue'], $config['class'], $config['args']); } else { $this->logger->log(Psr\Log\LogLevel::INFO, 'queueing {class} in {queue} [delayed]', array('class' => $config['class'], 'queue' => $config['queue'])); Resque_Event::trigger('beforeDelayedEnqueue', array('queue' => $config['queue'], 'class' => $config['class'], 'args' => $config['args'])); $payload = array_merge(array($config['queue'], $config['class']), $config['args']); call_user_func_array('Resque::enqueue', $payload); } }
/** * Perform necessary actions to start a worker. */ private function startup() { $this->registerSigHandlers(); $this->pruneDeadWorkers(); Resque_Event::trigger('beforeFirstFork', $this); $this->registerWorker(); }
/** * Create a new job and save it to the specified queue. * * @param string $queue The name of the queue to place the job in. * @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 $trackStatus Set to true to be able to monitor the status of a job. * * @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) { $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; } Resque_Job::create($queue, $class, $args, $trackStatus, $id); Resque_Event::trigger('afterEnqueue', $hookParams); return $id; }
/** * Create a new job and save it to the specified queue. * * @param string $queue The name of the queue to place the job in. * @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 $trackStatus Set to true to be able to monitor the status of a job. * @param string $method method name to invoke in job class. * @return string */ public static function enqueue($queue, $call, $args = null, $trackStatus = false, $method = 'fire') { if ($call instanceof Closure) { $serialized = serialize(new SerializableClosure($call)); $result = Resque_Job_Closure::create($queue, $serialized, $args, $trackStatus); if ($result) { Resque_Event::trigger('afterEnqueue', array('class' => $serialized, 'args' => $args, 'queue' => $queue, 'id' => $result)); } return $result; } $result = Resque_Job_Class::create($queue, $call, $args, $trackStatus, $method); if ($result) { Resque_Event::trigger('afterEnqueue', array('class' => $call, 'args' => $args, 'queue' => $queue, 'id' => $result, 'method' => $method)); } return $result; }
<?php use CultuurNet\UDB3\Log\ContextEnrichingLogger; require_once 'vendor/autoload.php'; Resque_Event::listen('beforePerform', function (Resque_Job $job) { /** @var \Silex\Application $app */ $app = (require __DIR__ . '/bootstrap.php'); $app->boot(); $args = $job->getArguments(); $context = unserialize(base64_decode($args['context'])); $app['impersonator']->impersonate($context); $app['logger.fatal_job_error'] = new ContextEnrichingLogger($app['logger.command_bus'], array('job_id' => $job->payload['id'])); $errorLoggingShutdownHandler = function () use($app) { $error = error_get_last(); $fatalErrors = E_ERROR | E_RECOVERABLE_ERROR; $wasFatal = $fatalErrors & $error['type']; if ($wasFatal) { $app['logger.fatal_job_error']->error('job_failed'); $app['logger.fatal_job_error']->debug('error caused job failure', ['error' => $error]); } }; register_shutdown_function($errorLoggingShutdownHandler); // Command bus service name is based on queue name + _command_bus_out. // Eg. Queue "event" => command bus "event_command_bus_out". $commandBusServiceName = getenv('QUEUE') . '_command_bus_out'; // Allows to access the command bus in perform() of jobs that // come out of the queue. \CultuurNet\UDB3\CommandHandling\QueueJob::setCommandBus($app[$commandBusServiceName]); });
public static function clearListeners() { \Resque_Event::clearListeners(); }
/** * Perform necessary actions to start a worker. */ protected function startup() { $this->log(array('message' => 'Starting worker ' . $this, 'data' => array('type' => 'start', 'worker' => (string) $this)), self::LOG_TYPE_INFO); $this->registerSigHandlers(); $this->pruneDeadWorkers(); Resque_Event::trigger('beforeFirstFork', $this); $this->registerWorker(); }
/** * Create a new job and save it to the specified queue. * * @param string $queue The name of the queue to place the job in. * @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 $trackStatus Set to true to be able to monitor the status of a job. * * @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) { if (self::$runInBackground) { $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; } Resque_Job::create($queue, $class, $args, $trackStatus, $id); Resque_Event::trigger('afterEnqueue', $hookParams); return $id; } else { $obj = new $class(); $obj->args = $args; if (method_exists($obj, 'setUp')) { $obj->setUp(); } if (method_exists($obj, 'perform')) { $obj->perform(); } if (method_exists($obj, 'tearDown')) { $obj->tearDown(); } return true; } }
/** * Call all registered listeners. */ public static function clearListeners() { self::$events = array(); }
<?php // Somewhere in our application, we need to register: Resque_Event::listen('afterEnqueue', array('My_Resque_Plugin', 'afterEnqueue')); Resque_Event::listen('beforeFirstFork', array('My_Resque_Plugin', 'beforeFirstFork')); Resque_Event::listen('beforeFork', array('My_Resque_Plugin', 'beforeFork')); Resque_Event::listen('afterFork', array('My_Resque_Plugin', 'afterFork')); Resque_Event::listen('beforePerform', array('My_Resque_Plugin', 'beforePerform')); Resque_Event::listen('afterPerform', array('My_Resque_Plugin', 'afterPerform')); Resque_Event::listen('onFailure', array('My_Resque_Plugin', 'onFailure')); class My_Resque_Plugin { public static function afterEnqueue($class, $arguments) { echo "Job was queued for " . $class . ". Arguments:"; print_r($arguments); } public static function beforeFirstFork($worker) { echo "Worker started. Listening on queues: " . implode(', ', $worker->queues(false)) . "\n"; } public static function beforeFork($job) { echo "Just about to fork to run " . $job; } public static function afterFork($job) { echo "Forked to run " . $job . ". This is the child process.\n"; } public static function beforePerform($job) {
<?php require_once 'vendor/autoload.php'; Resque_Event::listen('beforePerform', function (Resque_Job $job) { /** @var \Silex\Application $app */ $app = (require __DIR__ . '/bootstrap.php'); $app->boot(); $args = $job->getArguments(); $context = unserialize(base64_decode($args['context'])); $app['impersonator']->impersonate($context); // Allows to access the command bus in perform() of jobs that // come out of the queue. \CultuurNet\UDB3\CommandHandling\QueueJob::setCommandBus($app['event_command_bus']); });
/** * The method to run after a Job is finished. */ public function tearDown() { //Verificar si existen argumentos if (!empty($this->args)) { //Establecer variables self::$datetime = $this->args["datetime"]; self::$quequename = $this->args["quequename"]; self::$jobclassname = $this->args["jobclassname"]; self::$id_configuracion_reporte = $this->args["idNotificacionReporte"]; } //DB Conection self::$db = new Database(); self::$db->connect(); ///Fecha y Hora Actual //$current_datetime = new DateTime(date('Y-m-d H:i:s'), new DateTimeZone('America/Panama')) $current_datetime = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s'))); //Calcular nueva fecha para programar la tarea //Sumarle 7 dias a la fecha de Ejecucion //self::$datetime = date('Y-m-d H:i:s', strtotime($current_datetime. ' + 7 days')); self::$datetime = date('Y-m-d H:i:s', strtotime($current_datetime . '+20 minute')); //Actualizar fecha ultima fecha de ejecucion de la tarea //y fecha de proxima ejcucion $fields = array("ultimo_tiempo_ejecucion" => $current_datetime, "proximo_tiempo_ejecucion" => self::$datetime); self::$db->update('configuracion_notificaciones_reportes', $fields, 'id="' . $this->args["idNotificacionReporte"] . '"'); $result = self::$db->getResult(); //print echo "Proxima Fecha de Ejecucion: " . self::$datetime . PHP_EOL; $horas = strtotime(self::$datetime) - strtotime($current_datetime); //Agendar nuevamente el job ResqueScheduler::enqueueIn($horas, self::$quequename, self::$jobclassname, ['datetime' => self::$datetime, 'quequename' => self::$quequename, 'jobclassname' => self::$jobclassname, 'idNotificacionReporte' => "" . $this->args["idNotificacionReporte"] . ""]); //print echo "Proxima Fecha en Horas: " . $horas . PHP_EOL; Resque_Event::listen('afterPerform', function () { //echo "Se envio el correo :)) "; }); Resque_Event::listen('onFailure', function () { echo "Algo paso :-| ...."; }); }
public function tearDown() { $current_datetime = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s'))); $id_notificacion = $this->args['id']; $this->db->sql('SELECT * FROM notificaciones WHERE id="' . $id_notificacion . '" AND tipo = 0'); $results = $this->db->getResult(); if (!empty($results[0])) { $data = json_decode($results[0]['data']); $fecha_creacion_notificacion = $results[0]['fecha_creacion']; $fecha_oportunidad = $this->args['fecha_oportunidad']; $fecha_ejecucion = $this->args['tiempo_ejecucion']; $tiempo = Subordinados1::get_recurrencia($fecha_creacion_notificacion, $fecha_ejecucion); $condicion = split(" ", $tiempo); echo 'poner notificaciones en redis' . PHP_EOL; switch ($data->tipo) { case 'nueva_oportunidad': if ($condicion[0] >= 24 && ($condicion[1] == 'dias' || $condicion[1] == 'minutos' || $condicion[1] == 'horas')) { $current_datetime = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s ') . '24 hour')); $this->args['tiempo_ejecucion'] = $current_datetime; $datetime = new DateTime($current_datetime, new DateTimeZone('America/Panama')); ResqueScheduler::enqueueAt($datetime, 'notificacion' . time(), 'Notificaciones', $this->args); } break; case 'oportunidad_actualizar_etapa': if ($condicion[0] > 40 && ($condicion[1] == 'dias' || $condicion[1] == 'minutos' || $condicion[1] == 'horas')) { $current_datetime = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s ') . '5 day')); $this->args['tiempo_ejecucion'] = $current_datetime; $datetime = new DateTime($current_datetime, new DateTimeZone('America/Panama')); ResqueScheduler::enqueueAt($datetime, 'notificacion' . time(), 'Notificaciones', $this->args); } break; } } Resque_Event::listen('afterPerform', function () { echo "Se ejecuto la tarea Notificaciones {$this->args}['id'] " . date('Y-m-d H:i:s') . PHP_EOL; }); Resque_Event::listen('onFailure', function () { echo "Algo paso :-| ...."; }); }
/** * Schedule all of the delayed jobs for a given timestamp. * * Searches for all items for a given timestamp, pulls them off the list of * delayed jobs and pushes them across to Resque. * * @param DateTime|int $timestamp Search for any items up to this timestamp to schedule. */ public function enqueueDelayedItemsForTimestamp($timestamp) { $item = null; while ($item = ResqueScheduler::nextItemForTimestamp($timestamp)) { if ($timestamp instanceof DateTime) { $timestamp = $timestamp->getTimestamp(); } $this->logger->log(Psr\Log\LogLevel::NOTICE, 'Queueing {class} scheduled to {datetime} in {queue} queue with args {args}', array('class' => $item['class'], 'queue' => $item['queue'], 'args' => json_encode($item['args']), 'datetime' => date('Y-m-d H:i:s', $timestamp))); Resque_Event::trigger('beforeDelayedEnqueue', array('queue' => $item['queue'], 'class' => $item['class'], 'args' => $item['args'])); $payload = array_merge(array($item['queue'], $item['class']), $item['args']); call_user_func_array('Resque::enqueue', $payload); } }
/** * Setup container with App */ public function setUp() { $this->container = app(); \Resque_Event::listen('onFailure', array($this, 'onFailure')); }
/** * Create a new job and save it to the specified queue. * 创建一个Job并将它放入到队列中 * * @param string $queue The name of the queue to place the job in. * @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 $trackStatus Set to true to be able to monitor the status of a job. * * @return string */ public static function enqueue($queue, $class, $args = null, $trackStatus = false) { require_once dirname(__FILE__) . '/Resque/Job.php'; // 创建job $result = Resque_Job::create($queue, $class, $args, $trackStatus); if ($result) { // 触发入队的事件 Resque_Event::trigger('afterEnqueue', array('class' => $class, 'args' => $args, 'queue' => $queue)); } return $result; }
<?php Deprecation::notification_version('1.1.0', 'deploynaut'); // *.sspak is required for data archives $exts = Config::inst()->get('File', 'allowed_extensions'); $exts[] = 'sspak'; Config::inst()->update('File', 'allowed_extensions', $exts); // This will ensure jobs can correctly clean themselves up on any type of failure Resque_Event::listen('onFailure', function (Exception $exception, Resque_job $job) { $inst = $job->getInstance(); if ($inst instanceof DeploynautJobInterface) { $inst->onFailure($exception); } });