Record the end of the job details. Ignore the sonar job from artifically inflating
the queue counters.

@param  float  $startTime
@param  string  $jobName
@return void
505243
public function recordJobEnd($startTime, $jobName)
    {
        $endTime = round((microtime(true) - $startTime)*1000);

        $this->cache->add('eyewitness_q_process_time_'.$this->currentQueue->id, 0, 180);
        $this->cache->increment('eyewitness_q_process_time_'.$this->currentQueue->id, $endTime);

        if ($jobName !== "Eyewitness\\Eye\\Queue\\Jobs\\Sonar") {
            $this->cache->add('eyewitness_q_process_count_'.$this->currentQueue->id, 0, 180);
            $this->cache->increment('eyewitness_q_process_count_'.$this->currentQueue->id);
        }
    }
766883
public function record(ResolveInfo $resolveInfo, $start, $end): void
    {
        $this->resolverTraces [] = [
            'path' => $resolveInfo->path,
            'parentType' => $resolveInfo->parentType->name,
            'returnType' => $resolveInfo->returnType->__toString(),
            'fieldName' => $resolveInfo->fieldName,
            'startOffset' => $this->diffTimeInNanoseconds($this->requestStartPrecise, $start),
            'duration' => $this->diffTimeInNanoseconds($start, $end),
        ];
    }
434881
public function toIcal($starttime = null, $endtime = null, $filename = 'calendar.ics') {

		if (is_null($starttime)) {
			$starttime = time();
		}
		if (is_null($endtime)) {
			$endtime = strtotime('+1 year', $starttime);
		}

		$instances = $this->getAllEventInstances($starttime, $endtime, true, 'ical');

		$config = array(
			'unique_id' => $this->guid,
			// setting these explicitly until icalcreator bug #14 is solved
			'allowEmpty' => true,
			'nl' => "\r\n",
			'format' => 'iCal',
			'delimiter' => DIRECTORY_SEPARATOR,
			'filename' => $filename, // this is last until #14 is solved
		);

		$v = new vcalendar($config);
		$v->setProperty('method', 'PUBLISH');
		$v->setProperty("X-WR-CALNAME", implode(' - ', array(elgg_get_config('sitename'), $this->getDisplayName())));
		$v->setProperty("X-WR-CALDESC", strip_tags($this->description));
		$v->setProperty("X-WR-TIMEZONE", Util::UTC);
		foreach ($instances as $instance) {

			$e = & $v->newComponent('vevent');

			$organizer = elgg_extract('organizer', $instance, array());
			unset($instance['organizer']);

			$reminders = elgg_extract('reminders', $instance, array());
			unset($instance['reminders']);

			foreach ($instance as $property => $value) {
				$e->setProperty($property, $value);
			}

			if (!empty($organizer)) {
				if (is_email_address($organizer)) {
					$e->setProperty('organizer', $organizer);
				} else {
					$e->setProperty('organizer', elgg_get_site_entity()->email, array(
						'CN' => $organizer,
					));
				}
			}

			if (!empty($reminders)) {
				foreach ($reminders as $reminder) {
					$a = & $e->newComponent('valarm');
					$a->setProperty('action', 'DISPLAY');
					$a->setProperty('trigger', "-PT{$reminder}S");
				}
			}
		}

		$v->returnCalendar();
	}
1306043
public function removeReminders($starttime, $endtime, $all = false) {
		$starttime = sanitize_int($starttime);
		$endtime = sanitize_int($endtime);
		
		$options = array(
			'guid' => $this->guid,
			'annotation_names' => array('reminder'),
			'limit' => false
		);
		
		if (!$all) {
			$options['wheres'] = "CAST(v.string as SIGNED) BETWEEN {$starttime} AND {$endtime}";
		}
		
		return elgg_delete_annotations($options);
	}
245089
private function executeJob(Job $job)
    {
        $this->currentJobId = $job->getId();
        $job->setLogger($this->logger);
        $this->logger->notice("Starting job #" . $this->currentJobId);
        
        if (!function_exists('pcntl_fork')) {
            $this->runJob($job);
            return;
        }

        $pid = pcntl_fork();
        if ($pid) {
            pcntl_wait($status);
        } else {
            $this->runJob($job);
            die();
        }
    }
621817
public function createDelayed($name, \Closure $startCallback)
    {
        $childJob = $this->jobProcessor->findOrCreateChildJob($name, $this->rootJob);

        $this->jobExtension->onPreCreateDelayed($childJob);

        $jobRunner = $this->getJobRunnerForChildJob($this->rootJob);
        $createResult = call_user_func($startCallback, $jobRunner, $childJob);

        $this->jobExtension->onPostCreateDelayed($childJob, $createResult);

        return $createResult;
    }
605017
public function start(Job $job)
    {
        $jobData = new JobData();

        if ($this->exec) {
            $jobDir = $this->_getJobDirectory($job);
            $logFile = realpath($this->getDirectory()) . '/run.log';
            $lockFile = $this->_lockJob($jobDir);

            if ($lockFile) {
                // $jobdir = str_replace("/", DIRECTORY_SEPARATOR, $jobDir);

                $jobData->lockFile = $lockFile;
                $jobData->job = $job;
                $jobData->jobDir = $jobDir;

                $this->runningJobs[spl_object_hash($job)] = $jobData;

                $data = $job->getData();
                $data['___class'] = get_class($job);

                file_put_contents("$jobDir/in.serialize", serialize($data));

                $cmd = $this->getCmd('"'.realpath(__DIR__ . "/../../bin/AsynchronousJobsRun.php") . "\" $jobDir >> $logFile");
                if (substr(php_uname(), 0, 7) == "Windows") {
                    $WshShell = new \COM("WScript.Shell");
                    $WshShell->Run("$cmd /C dir /S %windir%", 0, false);
                } else {
                    exec($cmd . " &");
                }

            } else {
                $this->pendingJobs[] = $job;
            }
        }else {
            $job->run();
            $job->end($jobData);
        }
    }
113139
protected function get_time_range_weeks_number($starttime, $endtime) {
        if ($endtime <= $starttime) {
            throw new \coding_exception('End time timestamp should be greater than start time.');
        }

        $starttimedt = new \DateTime();
        $starttimedt->setTimestamp($starttime);
        $starttimedt->setTimezone(new \DateTimeZone('UTC'));
        $endtimedt = new \DateTime();
        $endtimedt->setTimestamp($endtime);
        $endtimedt->setTimezone(new \DateTimeZone('UTC'));

        $diff = $endtimedt->getTimestamp() - $starttimedt->getTimestamp();
        return $diff / WEEKSECS;
    }
895858
public function executeJob(Job $job, int $retryLimit = 0): void
    {
        // This is here so that if executeJob is called with out startBatch the events will still be called
        $this->triggerBatchEvents = !$this->batchStarted;
        if ($this->triggerBatchEvents) {
            $this->startBatch(new JobBatch([$job]));
        }

        $internal = false;

        if ($this->logger) {
            $this->logger->debug('Start a job.', [
                'name' => $job->getName(),
                'arguments' => $job->getArguments(),
            ]);
        }

        try {
            $worker = $this->workersMap->get($job->getName());
            if (!$worker instanceof Worker) {
                throw new InvalidWorkerException("The worker {$job->getName()} is not an instance of ".Worker::class);
            }
            $internal = $worker instanceof InternalWorker;
            if ($this->eventDispatcher) {
                $this->eventDispatcher->dispatch(self::JOB_START_EVENT, new StartJobEvent($job, $internal));
            }
            $worker->execute($job->getArguments());
        } catch (NotFoundExceptionInterface $e) {
            $unrecoverable = new UnrecoverableJobException("Missing worker {$job->getName()}", 0, $e);
            $this->failedJob($job, $unrecoverable, $internal);

            throw $unrecoverable;
        } catch (UnrecoverableJobExceptionInterface $e) {
            $this->failedJob($job, $e, $internal);

            throw $e;
        } catch (\Throwable $e) {
            if (!$job instanceof RetryableJob) {
                $unrecoverable = new UnrecoverableJobException('Job failed and is not retryable', 0, $e);
                $this->failedJob($job, $unrecoverable, $internal);

                throw $unrecoverable;
            }

            if ($job->getRetryCount() >= $retryLimit) {
                $unrecoverable = new UnrecoverableJobException('Job reached retry limit and won\'t be retried again', 0, $e);
                $this->failedJob($job, $unrecoverable, $internal);

                throw $unrecoverable;
            }

            $this->failedJob($job, $e, $internal);

            throw $e;
        }
        $this->finishJob($job, $internal);
    }
1057533
public function scanCompleted(Event $event, $startTime, $endTime, ResultScan $ResultScan)
    {
        if ($this->args->getOption('verbose')) {
            $this->io->hr();
        }

        $endTime = new Time($endTime);
        $elapsedTime = $endTime->diffForHumans(new Time($startTime), true);

        $this->io->out(__d('link-scanner', 'Scan completed at {0}', $endTime->i18nFormat('yyyy-MM-dd HH:mm:ss')));
        $this->io->out(__d('link-scanner', 'Elapsed time: {0}', $elapsedTime));
        $this->io->out(__d('link-scanner', 'Total scanned links: {0}', $ResultScan->count()));

        if ($this->args->getOption('verbose')) {
            $this->io->hr();
        }

        return true;
    }
681357
public function createDelayed($name, callable $startCallback)
    {
        $childJob = $this->jobProcessor->findOrCreateChildJob($name, $this->rootJob);

        $jobRunner = new self($this->jobProcessor, $this->rootJob);

        return call_user_func($startCallback, $jobRunner, $childJob);
    }
694518
public function perform(Job $job)
    {
        // Set timeout so as to stop any hanged jobs
        // and turn off displaying errors as it fills
        // up the console
        set_time_limit($this->timeout);
        ini_set('display_errors', 0);

        $job->perform();

        $status = $job->getStatus();

        switch ($status) {
            case Job::STATUS_COMPLETE:
                $this->log('Done job <pop>'.$job.'</pop> in <pop>'.$job->execTimeStr().'</pop>', Logger::INFO);
                break;
            case Job::STATUS_CANCELLED:
                $this->log('Cancelled job <pop>'.$job.'</pop>', Logger::INFO);
                break;

            case Job::STATUS_FAILED:
                $this->log('Job '.$job.' failed: "'.$job->failError().'" in '.$job->execTimeStr(), Logger::ERROR);
                break;
            default:
                $this->log('Unknown job status "('.gettype($status).')'.$status.'" for <pop>'.$job.'</pop>', Logger::WARNING);
                break;
        }
    }
1046797
public function setPeriod(\DateTime $start = null, \DateTime $end = null)
    {
        $this->filters['start'] = $start !== null? $start->format('c') : null;
        $this->filters['end'] = $end !== null ? $end->format('c') : null;
    }
931637
public function delete(Job $job)
    {
        $this->pheanstalk->delete($job);

        $this->logJob($job->getId(), 'Job deleted');
    }
1243134
protected function setFinishData(array &$result, array &$job)
    {
        $result['message'] = $job['message']['finish'];

        $this->setFinishDataErrors($result, $job);
        $this->setFinishDataNoErrors($result, $job);
    }
1196746
public static function fromString($startTime, $endTime)
    {
        return new self(Time::fromString($startTime), Time::fromString($endTime));
    }
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;
        }
    }