Get the times in milliseconds needed to clear the queues.

@param  \Laravel\Horizon\Supervisor  $supervisor
@param  \Illuminate\Support\Collection  $pools
@return \Illuminate\Support\Collection
516317
protected function timeToClearPerQueue(Supervisor $supervisor, Collection $pools)
    {
        return $pools->mapWithKeys(function ($pool, $queue) use ($supervisor) {
            $size = $this->queue->connection($supervisor->options->connection)->readyNow($queue);

            return [$queue => ($size * $this->metrics->runtimeForQueue($queue))];
        });
    }
1135185
public function clear()
    {
        return PoolManager::use($this->poolName, function($resource, \Imi\Redis\RedisHandler $redis){
            return $redis->flushDB();
        });
    }
503749
public function maxTimeMS($ms)
    {
        $this->maxTimeMS = (integer) $ms;
        $this->mongoCursor->maxTimeMS($this->maxTimeMS);
        return $this;
    }
279594
public function process($connection, Job $job, $maxTries = 0, $delay = 0)
    {
        $startTime = microtime(true);
        $result = null;

        try {
            $result = parent::process($connection, $job, $maxTries, $delay);
        } catch (Exception $e) {
            $this->recordJobException($e);
        } catch (Throwable $e) {
            $this->recordJobException($e);
        } finally {
            $this->recordJobEnd($startTime, $job->resolveName());
            return $result;
        }
    }
132460
protected function removeExpiredJobs($transaction, $from, $time)
    {
        $transaction->multi();

        $transaction->zremrangebyscore($from, '-inf', $time);
    }
87283
public function monitoring()
    {
        return collect(app(SupervisorRepository::class)->all())
            ->pluck('pid')
            ->pipe(function ($processes) {
                $processes->each(function ($process) use (&$processes) {
                    $processes = $processes->merge($this->exec->run("pgrep -P {$process}"));
                });

                return $processes;
            })
            ->merge(
                Arr::pluck(app(MasterSupervisorRepository::class)->all(), 'pid')
            )->all();
    }
971769
private function setupPools(ContainerBuilder $container)
    {
        $pools = $container->getParameter('gendoria_command_queue.pools');
        $usedServiceIds = array();
        foreach ($pools as $poolData) {
            $sendServiceId = substr($poolData['send_driver'], 1);
            if (in_array($sendServiceId, $usedServiceIds)) {
                throw new InvalidArgumentException(sprintf(
                    'Each pool has to have unique send service - duplicate service id "%s" found.',
                    $sendServiceId
                ));
            }
            if (!$container->hasDefinition($sendServiceId)) {
                throw new InvalidArgumentException('Non existing send driver service provided: ' . $poolData['send_driver'].'.');
            }
            $sendDriverReflection = new ReflectionClass($container->getDefinition($sendServiceId)->getClass());
            if (!$sendDriverReflection->implementsInterface(SendDriverInterface::class)) {
                throw new InvalidArgumentException(sprintf(
                    'Service "%s" does not implement interface "%s".',
                    $sendServiceId,
                    SendDriverInterface::class
                ));
            }
            $usedServiceIds[] = $sendServiceId;
        }
    }
1061170
synchronized int removeOldConnections() {
        long now = System.currentTimeMillis();
        long expirationTime = now - idleTransportTimeout.millis();

        List<PooledTransport> removeFromIdle = new ArrayList<PooledTransport>();
        for (Map.Entry<PooledTransport, Long> idleEntry : idle.entrySet()) {
            long lastUsed = idleEntry.getValue();
            if (lastUsed < expirationTime) {
                PooledTransport removed = idleEntry.getKey();
                if (log.isTraceEnabled()) {
                    log.trace("Expiring idle transport for job [" + jobPoolingKey + "], transport: ["
                            + removed.toString() + "]. Last used [" + new TimeValue(now-lastUsed) + "] ago. Expired ["
                            + idleTransportTimeout + "] ago.");
                }
                release(removed);
                removeFromIdle.add(removed);
            }
        }

        for (PooledTransport toRemove : removeFromIdle) {
            idle.remove(toRemove);
        }

        return idle.size() + leased.size();
    }
798778
public function handle(MasterSupervisorRepository $masters)
    {
        $masters = $masters->all();

        if (empty($masters)) {
            return $this->info('No machines are running.');
        }

        $this->table([
            'Name', 'PID', 'Supervisors', 'Status',
        ], collect($masters)->map(function ($master) {
            return [
                $master->name,
                $master->pid,
                $master->supervisors ? collect($master->supervisors)->map(function ($supervisor) {
                    return explode(':', $supervisor, 2)[1];
                })->implode(', ') : 'None',
                $master->status,
            ];
        })->all());
    }
181132
protected function __tryLock()
    {
        return PoolManager::use($this->poolName, function($resource, $redis){
            return 1 == $redis->evalEx(<<<SCRIPT
local key     = KEYS[1]
local content = KEYS[2]
local ttl     = ARGV[2]
local db      = ARGV[1]
redis.call('select', db)
local lockSet = redis.call('setnx', key, content)
if lockSet == 1 then
redis.call('pexpire', key, ttl)
else 
local value = redis.call('get', key)
if(value == content) then
lockSet = 1;
redis.call('pexpire', key, ttl)
end
end
return lockSet
SCRIPT
            , [
                $this->key,
                $this->guid,
                $this->db,
                $this->lockExpire,
            ], 2);
        });
    }
1115795
public function orphanedFor($master, $seconds)
    {
        $expiresAt = Chronos::now()->getTimestamp() - $seconds;

        return collect($this->allOrphans($master))->filter(function ($recordedAt, $_) use ($expiresAt) {
            return $expiresAt > $recordedAt;
        })->keys()->all();
    }
127982
public function clearProcessLogAction($key, $name, $group)
    {
        $supervisorManager = $this->get('supervisor.manager');
        $supervisor = $supervisorManager->getSupervisorByKey($key);
        $process = $supervisor->getProcessByNameAndGroup($name, $group);

        if (!$supervisor) {
            throw new \Exception('Supervisor not found');
        }

        if ($process->clearProcessLogs() !== true) {
            $this->get('session')->getFlashBag()->add(
                'error',
                $this->get('translator')->trans('logs.delete.error', array(), 'YZSupervisorBundle')
            );
        }

        return $this->redirect($this->generateUrl('supervisor'));
    }
1157110
private function processes()
    {
        return collect($this->supervisors->all())->pluck('processes')->reduce(function ($final, $queues) {
            foreach ($queues as $queue => $processes) {
                $final[$queue] = isset($final[$queue]) ? $final[$queue] + $processes : $processes;
            }

            return $final;
        }, []);
    }
370996
protected function createProcessPool(SupervisorOptions $options)
    {
        return new ProcessPool($options, function ($type, $line) {
            $this->output($type, $line);
        });
    }
1097404
public function setRedisPools($redisPools)
    {
        if (!empty($this->redisPools)) {
            foreach ($this->redisPools as $k => &$pool) {
                $pool->destroy();
                $poll = null;
            }
        }

        $this->redisPools = $redisPools;
        return $this;
    }
85770
public function getTokenResult($token, callable $set = null)
    {
        return Pool::getInstance()->get(ClusterCoroutine::class)->init($token, $this->receive_call, $set);
    }
1297617
public function getPointsSinceMinutes(Metric $metric, $minutes)
    {
        $queryType = $this->getQueryType($metric);

        $points = DB::select("SELECT DATE_FORMAT({$this->getMetricPointsTable()}.`created_at`, '%Y-%m-%d %H:%i') AS `key`, {$queryType} ".
            "FROM {$this->getMetricsTable()} INNER JOIN {$this->getMetricPointsTable()} ON {$this->getMetricsTable()}.id = {$this->getMetricPointsTable()}.metric_id ".
            "WHERE {$this->getMetricsTable()}.id = :metricId ".
            "AND {$this->getMetricPointsTable()}.`created_at` >= DATE_SUB(NOW(), INTERVAL :minutes MINUTE) ".
            "AND {$this->getMetricPointsTable()}.`created_at` <= NOW() ".
            "GROUP BY HOUR({$this->getMetricPointsTable()}.`created_at`), MINUTE({$this->getMetricPointsTable()}.`created_at`) ORDER BY {$this->getMetricPointsTable()}.`created_at`", [
            'metricId' => $metric->id,
            'minutes'  => $minutes,
        ]);

        return $this->mapResults($metric, $points);
    }