Starts the execution in the state machine and returns
the generated executionArn from AWS.

@param int    $timestamp
@param string $jobId

@return string

@throws SchedulerOperationFailed
430286
private function startExecution(int $timestamp, string $jobId): string
    {
        $start = new \DateTime('now', new \DateTimeZone('UTC'));
        $sendAt = new \DateTime("@{$timestamp}");
        $span = (int)$start->diff($sendAt)->format('%a');

        $input = ['job_id' => $jobId];

        /*
         * AWS Step Functions have a one year maximum execution time.
         * Rather than artificially limit our sendAt dates to 1 year
         * in the future we'll just restart the executions when we
         * encounter this scenario.
         */
        if ($span < 365) {
            $input['send_at'] = $sendAt->format(self::DATE_FORMAT);
        } else {
            // just a skosh behind 1 year to fly under the radar
            $start->modify('+364 days');
            $input['resend_at'] = [];

            do {
                $input['resend_at'][] = $start->format(self::DATE_FORMAT);
                $start->modify('+364 days');
            } while ($start < $sendAt);

            // the original sendAt is the last one to "resend"
            $input['resend_at'][] = $sendAt->format(self::DATE_FORMAT);
            $input['send_at'] = array_shift($input['resend_at']);
        }

        try {
            $result = $this->sfnClient->startExecution([
                'stateMachineArn' => $this->stateMachineArn,
                'input'           => json_encode($input),
            ]);

            return $result['executionArn'];
        } catch (\Throwable $t) {
            if ($t instanceof AwsException) {
                $errorName = $t->getAwsErrorCode() ?: ClassUtils::getShortName($t);
                switch ($errorName) {
                    case 'ExecutionLimitExceeded':
                        $code = Code::RESOURCE_EXHAUSTED;
                        break;

                    case 'ExecutionAlreadyExists':
                        $code = Code::ALREADY_EXISTS;
                        break;

                    case 'InvalidArn':
                    case 'InvalidExecutionInput':
                    case 'InvalidName':
                        $code = Code::INVALID_ARGUMENT;
                        break;

                    case 'StateMachineDoesNotExist':
                    case 'StateMachineDeleting':
                        $code = Code::NOT_FOUND;
                        break;

                    default:
                        $code = Code::UNAVAILABLE;
                        break;
                }
            } else {
                $errorName = ClassUtils::getShortName($t);
                $code = Code::INTERNAL;
            }

            throw new SchedulerOperationFailed(
                sprintf(
                    '%s while adding to state machine [%s] for job_id [%s].',
                    $errorName,
                    $this->stateMachineArn,
                    $jobId
                ),
                $code,
                $t
            );
        }
    }
685326
public function timestamp(SchedulerInterface $scheduler = null): Observable
    {
        return $this->lift(function () use ($scheduler) {
            return new TimestampOperator($scheduler ?: Scheduler::getDefault());
        });
    }
1098535
public function timeslice(int $timestamp = null):int{
		return (int)floor(($timestamp ?? time()) / $this->options->period);
	}
610763
public function start($args = null, $scheduler = false)
    {
        if ($args === null) {
            $this->outputTitle($scheduler ? 'Creating the scheduler worker' : 'Creating workers');
        } else {
            $this->runtime = $args;
        }

        if ($scheduler) {
            if ($this->runtime['Scheduler']['enabled'] !== true) {
                $this->output->outputLine('Scheduler Worker is not enabled', 'failure');
                return false;
            }

            if ($this->ResqueStatus->isRunningSchedulerWorker()) {
                $this->output->outputLine('The scheduler worker is already running', 'warning');
                return false;
            }

            $args['type'] = 'scheduler';
        }


        $pidFile = (isset($this->runtime['Fresque']['tmpdir']) ?
                        $this->runtime['Fresque']['tmpdir'] : dirname(__DIR__) . DS . 'tmp' )
                        . DS . str_replace('.', '', microtime(true));
        $count = $this->runtime['Default']['workers'];

        $this->debug('Will start ' . $count . ' workers');

        for ($i = 1; $i <= $count; $i++) {

            $libraryPath = $scheduler ? $this->runtime['Scheduler']['lib'] : $this->runtime['Fresque']['lib'];
            $logFile = $scheduler ? $this->runtime['Scheduler']['log'] : $this->runtime['Log']['filename'];
            $resqueBin = $scheduler ? './bin/resque-scheduler.php' : $this->getResqueBinFile($this->runtime['Fresque']['lib']);

            $libraryPath = rtrim($libraryPath, '/');

            // build environment variables string to be passed to the worker
            $env_vars = "";
            foreach($this->runtime['Env'] as $env_name => $env_value) {
                // if only the name is supplied, we get the value from environment
                if (strlen($env_value) == 0) {
                    $env_value = getenv($env_name);
                }
                $env_vars .= $env_name . '=' . escapeshellarg($env_value) . " \\\n";
            }

            $cmd = 'nohup ' . ($this->runtime['Default']['user'] !== $this->getProcessOwner() ? ('sudo -u '. escapeshellarg($this->runtime['Default']['user'])) : "") . " \\\n".
            'bash -c "cd ' .
            escapeshellarg($libraryPath) . '; ' . " \\\n".
            $env_vars .
            (($this->runtime['Default']['verbose']) ? 'VVERBOSE' : 'VERBOSE') . '=true ' . " \\\n".
            'QUEUE=' . escapeshellarg($this->runtime['Default']['queue']) . " \\\n".
            'PIDFILE=' . escapeshellarg($pidFile) . " \\\n".
            'APP_INCLUDE=' . escapeshellarg($this->runtime['Fresque']['include']) . " \\\n".
            'RESQUE_PHP=' . escapeshellarg($this->runtime['Fresque']['lib'] . DS . 'lib' . DS . 'Resque.php') . " \\\n".
            'INTERVAL=' . escapeshellarg($this->runtime['Default']['interval']) . " \\\n".
            'REDIS_BACKEND=' . escapeshellarg($this->runtime['Redis']['host'] . ':' . $this->runtime['Redis']['port']) . " \\\n".
            'REDIS_DATABASE=' . escapeshellarg($this->runtime['Redis']['database']) . " \\\n".
            'REDIS_NAMESPACE=' . escapeshellarg($this->runtime['Redis']['namespace']) . " \\\n".
            'REDIS_PASSWORD=' . escapeshellarg($this->runtime['Redis']['password']) . " \\\n".
            'COUNT=' . 1 . " \\\n".
            'LOGHANDLER=' . escapeshellarg($this->runtime['Log']['handler']) . " \\\n".
            'LOGHANDLERTARGET=' . escapeshellarg($this->runtime['Log']['target']) . " \\\n".
            'php ' . escapeshellarg($resqueBin) . " \\\n";
            $cmd .= ' >> '. escapeshellarg($logFile).' 2>&1" >/dev/null 2>&1 &';

            $this->debug('Starting worker (' . $i . ')');
            $this->debug("Running command :\n\t" . str_replace("\n", "\n\t", $cmd));

            $this->exec($cmd);

            $this->output->outputText($scheduler ? 'Starting scheduler worker ' : 'Starting worker ');

            $success = false;
            $attempt = 7;
            while ($attempt-- > 0) {
                for ($x = 0; $x < 3; $x++) {
                    $this->output->outputText(".", 0);
                    usleep(self::$checkStartedWorkerBufferTime);
                }

                if (false !== $pid = $this->checkStartedWorker($pidFile)) {

                    $success = true;
                    $this->output->outputLine(' Done', 'success');

                    $this->debug('Registering worker #' . $pid . ' to list of active workers');

                    $workerSettings = $this->runtime;
                    $workerSettings['workers'] = 1;
                    if ($scheduler) {
                        $this->ResqueStatus->registerSchedulerWorker($pid);
                    }
                    $this->ResqueStatus->addWorker($pid, $workerSettings);

                    break;
                }
            }

            if (!$success) {
                $this->output->outputLine(' Fail', 'failure');
            }
        }

        if ($args === null) {
            $this->output->outputLine();
        }
    }
1213954
public function push($workerClass, array $args = [], $retry = false, $priority = 0, $at = null, $jobId = null) :? Job
    {
        $job = new Job($this, $jobId);

        $status = $job->schedule($workerClass, $args, $retry, $priority, $at);

        if ($status) {
            return $job;
        }

        return false;
    }
353586
public function expireat($key, $timestamp)
    {
        $this->init();
        $result = $this->driver->expireat($key, $timestamp);
        return (bool)$result;
    }
1160901
protected function execute(InputInterface $input, OutputInterface $output) : int
    {
        parent::execute($input, $output);

        $this->output->writeln('job process started');

        $this->queue->consume(Envelope::callback(function (Message $message, Envelope $envelope = null) {
            return $this->consumeCallback($message, $envelope);
        }));

        return $this->sendExitCode();
    }
241864
public function getJobStatus($jobId) {

        $data["Envelope"] = array(
            "Body" => array(
                "GetJobStatus" => array(
                    "JOB_ID" => $jobId
                ),
            ),
        );

        $response = $this->_request($data);
        $result = $response["Envelope"]["Body"]["RESULT"];

        if ($this->_isSuccess($result)) {
            if (isset($result['JOB_STATUS']))
                return $result;
            else {
                throw new Exception('Job status query was successful but no status was found.');
            }
        } else {
            throw new \Exception("getJobStatus Error: ".$this->_getErrorFromResponse($response));
        }

    }
908204
public function fromMemcachedTimestamp($timestamp) : DateTime
    {
        $date = DateTime::createFromFormat('U', $timestamp);
        $date->setTimezone(new DateTimeZone(date_default_timezone_get()));

        return $date;
    }
341032
public static function fromTimestamp($timestamp)
    {
        try {
            $dateTime = new DateTime("@{$timestamp}");

            return static::fromDateTime($dateTime);
        } catch (Exception $e) {
            throw new InvalidArgumentValue('$timestamp', $timestamp, __CLASS__, $e);
        }
    }
728658
@Override
	public JobExecutionResult execute(String jobName) throws Exception {
		PlanExecutor executor = getExecutor();

		Plan p = createProgramPlan(jobName);

		// Session management is disabled, revert this commit to enable
		//p.setJobId(jobID);
		//p.setSessionTimeout(sessionTimeout);

		JobExecutionResult result = executor.executePlan(p);

		this.lastJobExecutionResult = result;
		return result;
	}
1294355
public synchronized void runNow(String scheduledJobId) {
    ScheduledJob scheduledJob = getJob(scheduledJobId);

    try {
      JobKey jobKey = new JobKey(scheduledJobId, SCHEDULED_JOB_GROUP);
      if (quartzScheduler.checkExists(jobKey)) {
        // Run job now
        quartzScheduler.triggerJob(jobKey);
      } else {
        // Schedule with 'now' trigger
        Trigger trigger =
            newTrigger().withIdentity(scheduledJobId, SCHEDULED_JOB_GROUP).startNow().build();
        schedule(scheduledJob, trigger);
      }
    } catch (SchedulerException e) {
      LOG.error("Error runNow ScheduledJob", e);
      throw new MolgenisDataException("Error job runNow", e);
    }
  }
281573
public function expireAt($key, $timestamp) {
        return $this->getHandler($this->judge(__FUNCTION__))->expireAt($key, $timestamp);
    }
1359551
private function getTimestamp($timestamp)
    {
        if ($timestamp instanceof \DateTime) {
            $timestamp = $timestamp->getTimestamp();
        }

        if ((int)$timestamp != $timestamp) {
            throw new ResqueSchedulerInvalidTimestampException(
                'The supplied timestamp value could not be converted to an integer.'
            );
        }

        return (int)$timestamp;
    }
91243
public static function fromTimestamp(int $timestamp, ?string $timezone = null): Date
    {
        $timezone = $timezone ?: date_default_timezone_get();
        assert(Validate::isTimezone($timezone), sprintf('Invalid timezone: %s', $timezone));

        $time = sprintf('%d', $timestamp);
        $dateTime = DateTimeImmutable::createFromFormat('U', $time, new DateTimeZone('UTC'));
        $dateTime = $dateTime->setTimezone(new DateTimeZone($timezone));
        $year = (int) $dateTime->format('Y');
        $month = (int) $dateTime->format('n');
        $day = (int) $dateTime->format('j');

        return new static($year, $month, $day);
    }
420001
public function deferredDispatch($jobId, $command)
    {
        $exception = null;
        $currentCommandLogger = null;
        if ($this->logger) {
            $jobMetadata = array(
                'job_id' => $jobId,
            );
            $currentCommandLogger = new ContextEnrichingLogger(
                $this->logger,
                $jobMetadata
            );
        }

        if ($currentCommandLogger) {
            $currentCommandLogger->info('job_started');
        }

        if ($this->decoratee instanceof LoggerAwareInterface) {
            $this->decoratee->setLogger($currentCommandLogger);
        }

        try {
            parent::dispatch($command);
        } catch (\Exception $e) {
            if ($currentCommandLogger) {
                $currentCommandLogger->error('job_failed');

                $currentCommandLogger->debug(
                    'exception caused job failure',
                    ['exception' => $e]
                );
            }
            $exception = $e;
        }

        $this->setContext(null);

        if ($currentCommandLogger) {
            $currentCommandLogger->info('job_finished');
        }

        if ($exception) {
            throw $exception;
        }
    }
540414
public function peek($jobId)
	{
		$response = $this->_dispatch(
			new Pheanstalk_Command_PeekCommand($jobId)
		);

		return new Pheanstalk_Job($response['id'], $response['jobdata']);
	}