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'); }
/** * 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'); }
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 static function __callstatic($method, $args) { if (!self::isCallableEvent($method)) { if (strpos($method, 'Stop') !== false) { return self::stopEvent($method, $args); } throw new PHPResqueEventException("The {$method} does not exists"); } if (!\Resque_Event::listen($method, $args)) { throw new PHPResqueEventException("The {$method} cannot be registered."); } }
/** * 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 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 :-| ...."; }); }
<?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); } });
/** * 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 :-| ...."; }); }
<?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]); });
/** * Setup container with App */ public function setUp() { $this->container = app(); \Resque_Event::listen('onFailure', array($this, 'onFailure')); }
<?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']); });
<?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 if (!class_exists('RooftopJob')) { Resque_Event::listen('afterPerform', array('RooftopJob', 'afterPerform')); abstract class RooftopJob { public static function afterPerform($job) { // always perform this after perform() is called on a RooftopJob } public abstract function perform(); } }
<?php // Determine whether there is a testsession currently running, and if so - setup the persistent details for it. Injector::inst()->get('TestSessionEnvironment')->loadFromFile(); /** * This closure will run every time a Resque_Event is forked (just before it is forked, so it applies to the parent * and child process). */ if (class_exists('Resque_Event') && class_exists('SSResqueRun')) { Resque_Event::listen('beforeFork', function ($data) { global $databaseConfig; // Reconnect to the database - this may connect to the old DB first, but is required because these processes // are long-lived, and MySQL connections often get closed in between worker runs. We need to connect before // calling {@link TestSessionEnvironment::loadFromFile()}. DB::connect($databaseConfig); $testEnv = Injector::inst()->get('TestSessionEnvironment'); if ($testEnv->isRunningTests()) { $testEnv->loadFromFile(); } else { $testEnv->endTestSession(); } }); }