Deregister on worker exit.

@param WorkerInterface $worker The worker to wait for exit and then deregister.
@throws ResqueRuntimeException when $worker fails to exit cleanly.
@return void
165117
public function deregisterOnWorkerExit(WorkerInterface $worker)
    {
        $process = $worker->getProcess();
        $process->wait();
        if ($process->isCleanExit()) {
            $this->registry->deregister($worker);
        } else {
            throw new ResqueRuntimeException(
                sprintf(
                    'Foreman error with worker %s wait on pid %d',
                    $worker->getId(),
                    $process->getPid()
                )
            );
        }
    }
1335927
public function handle(JobDeleted $event)
    {
        if ($event->job->hasFailed()) {
            return;
        }

        $time = $this->watch->check($event->payload->id());

        $this->metrics->incrementQueue(
            $event->job->getQueue(), $time
        );

        $this->metrics->incrementJob(
            $event->payload->displayName(), $time
        );
    }
1187014
public function setTask(AbstractWorker $worker, $data): void
    {
        $key = sprintf('worker:%s', $worker->getId());

        $this->client->set($key, json_encode($data));
    }
74320
private function deleteStats($worker)
    {
        $processed = sprintf('processed:%s', $worker);
        $failed = sprintf('failed:%s', $worker);
        $this->client->del([$processed, $failed]);
    }
1020528
protected function execute(
        InputInterface $input,
        OutputInterface $output
    ) {
        $this->initialiseWorker($input, $output);
        $this->verboseOutput("<info>Starting up</info>");
        while ($this->keepWorking) {
            //do stuff
            //check if the processes are still working
            foreach ($this->family as $key => &$child) {
                $this->handle($key, $child);
            }
            $this->familyPlanning();
            //go to sleep for a bit
            usleep(100000);
        }
        $this->verboseOutput("<info>DONE!</info>");
    }
1159351
protected function purgeWorkers()
    {
        $timeoutHeartbeat = 5000;
        $timeoutExpiry    = 10000;

        $time        = microtime(true);
        $heartbeatAt = $time - ($timeoutHeartbeat / 1000);
        $expiryAt    = $time - ($timeoutExpiry / 1000);
        /* @var $worker Worker */
        foreach ($this->workers as $id => $worker) {
            if ($expiryAt > $worker->getActivityAt()) {
                $worker->setValid(false);
                $this->getLogger()->info(
                    'Worker '.$worker->getHexId().' invalid because of a timeout.'
                );
            }

            if (!$worker->isValid()) {
                /**
                 * Worker did not respond to heartbeats. No need to send destroy
                 * message, because it is not going to respond anyway.
                 *
                 * So lets just make the worker invalid for all the actions,
                 * and remove it from the manager.
                 */
                $worker->setValid(false);

                // Worker crashed, add the request in front of the queue.
                $request = $worker->getRequest();
                if ($request !== null) {
                    if ($request->retry() > 2) {
                        $this->getLogger()->info(
                            'To many retries for: '.$request->getActionName().' ('.$request->getId().').'
                        );
                        $this->storage[$request->getId()] = 'STATUS:500:Poison';
                    } else {
                        array_unshift($this->clientRequests[$request->getActionName()], $request);
                    }
                }
                unset($this->workers[$id]);
                continue;
            }

            if ($worker->isReady() && $heartbeatAt > $worker->getActivityAt()) {
                // Worker is idle, send a heartbeat.
                $this->reply($worker, new HeartbeatResponseWorkerhandler());
            }
        }
    }
545120
public function unregisterWorker()
    {
        if(is_object($this->currentJob)) {
            $this->currentJob->fail(new DirtyExitException);
        }

        $id = (string)$this;
        Resque::redis()->srem('workers', $id);
        Resque::redis()->del('worker:' . $id);
        Resque::redis()->del('worker:' . $id . ':started');
        Stat::clear('processed:' . $id);
        Stat::clear('failed:' . $id);
    }
1340730
public function handle(EventInterface $event): void
    {
        if ($this->queue === null) {
            throw new \RuntimeException('Property PublishToQueueListener::queue must be set');
        }

        try {
            $message = $this->createMessage($event);
            $this->getChannel()->basic_publish($message, '', $this->queue);
        } catch (InvalidConfigException $exception) {
            $this->logger->critical($exception->getMessage());
        }
    }
908539
public function deregister(string $name, bool $includeAlias = true): ManagerInterface
    {
        $shortcode = $this->shortcodes[$name] ?? false;
        if ($shortcode && $shortcode instanceof AliasInterface) {
            if ($name === $shortcode->getName() && $includeAlias) {
                foreach ($shortcode->getAlias() as $alias) {
                    parent::deregister($alias);
                }
            }
        }

        return parent::deregister($name);
    }
1256236
public function process(JobInterface $job, $maxTries = 0, $delay = 0)
    {
        if ($maxTries > 0 && $job->attempts() > $maxTries) {
            $this->fail($job);
            return Result::failed($job);
        }

        try {
            $job->fire();
            return Result::success($job);
        } catch (Exception $e) {
            // If we catch an exception, we will attempt to release the job back onto
            // the queue so it is not lost. This will let is be retried at a later
            // time by another listener (or the same one). We will do that here.
            if (!$job->isDeleted()) {
                $job->release($delay);
            }
            throw $e;
        } // @codeCoverageIgnoreStart
        catch (Throwable $e) {
            if (!$job->isDeleted()) {
                $job->release($delay);
            }
            throw $e;
        }
        // @codeCoverageIgnoreEnd
    }
527961
public function removeWorker(Worker $worker)
    {
        $this->commander->runSync(new WorkerDelete($worker->getClient()), 5);
        $this->workerPool->remove($worker);
        // TODO
        // нужно запилить механизм перехвата невыполненных задач
        /*foreach ($this->tasks as $name => $workers) {
            if (isset($workers[$dsc])) {
                unset($this->tasks[$name][$dsc]);
            }
        }*/
    }
194572
public function detach(ObserverInterface $observer)
    {
        $observers = $this->getObservers();

        foreach ($observer->getEvents() as $event) {
            $count = count($observers[$event]);

            for ($i = 0; $i < $count; $i++) {
                if ($observers[$event][$i] == $observer) {
                    unset($observers[$event][$i]);
                }
            }
        }

        $this->setObservers($observers);
    }
450275
protected function handleWorker(WorkerInterface $worker, $object, StorageInterface $storage)
    {
        $this->injectDependencies($worker);

        $modifiedObject = $worker->handle($object);

        if ($modifiedObject === null && $object !== null) {
            $storage->remove($object);
        } elseif ($modifiedObject !== $object) {
            $storage->remove($object);
            $storage->add($modifiedObject);
        }

        return $modifiedObject;
    }
82947
public function deleteReserved($queue, $job)
    {
        $this->getConnection()->zRem($this->getQueue($queue) . ':reserved', $job);
    }
599926
public static function exists($resqueInst, $workerId)
    {
        $class = get_called_class();
        if (isset($class) && !empty($class) && method_exists($class, 'workerName')) {
            $workerName = call_user_func($class . '::workerName');
            return (bool)$resqueInst->redis->sismember($workerName . 's', $workerId);
        } else {
            throw new ResqueWorkerInvalidException(['method workerName not exist in child class']);
        }
    }
427425
public function delete(TaskInterface $task)
    {
        $this->doDelete($task->getMetadata('RdsMessageId'), [
            'InternalMessageId' => $task->getId(),
            'RdsMessageId' => $task->getMetadata('RdsMessageId')
        ]);
    }
193893
public function onClose(ConnectionInterface $connection)
    {
        $client = $this->clients->findByConnection($connection);

        if ($client) {
            $this->clients->remove($client);

            $this->command->info('Client disconnected');

            // Fire the event.
            Event::fire(new ClientDisconnected($this->server, $this->clients, $client));
        }
    }