Start cron schedule

@param string $jobCode
@param int $status
@param null $messages

@return bool
541987
public function startCronSchedule($jobCode, $status = CronScheduleStatus::RUN, $messages = null)
    {
        $this->jobCode = $jobCode;
        $this->status = $status;
        $this->messages = $messages;
        $this->dateCreated = Yii::$app->formatter->asDatetime(time(), 'php: Y-m-d H:i:s');

        return $this->save();
    }
727600
public function findRootJobByJobNameAndStatuses($jobName, array $statuses)
    {
        return $this->createJobQueryBuilder('job')
            ->where('job.rootJob is NULL and job.name = :jobName and job.status in (:statuses)')
            ->andWhere('job.interrupted != true')
            ->setParameter('jobName', $jobName)
            ->setParameter('statuses', $statuses)
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }
1353802
public static function send($message = '', $status = 200)
    {
        if (self::$response === null) {
            self::init();
        }

        self::$response->setStatusCode(intval($status));
        self::$response->setContent(strval($message));
        self::$response->send();
    }
1168974
protected function collectJob(array $job, int $status, $from_status = JobInterface::STATUS_WAITING): bool
    {
        $set = [
             'status' => $status,
        ];

        if (JobInterface::STATUS_PROCESSING === $status) {
            $set['started'] = new UTCDateTime();
            $set['worker'] = $this->id;
        }

        $result = $this->db->{$this->scheduler->getJobQueue()}->updateMany([
            '_id' => $job['_id'],
            'status' => $from_status,
            '$isolated' => true,
        ], [
            '$set' => $set,
        ]);

        $this->logger->debug('collect job ['.$job['_id'].'] with status ['.$from_status.']', [
            'category' => get_class($this),
            'pm' => $this->process,
        ]);

        if (1 === $result->getModifiedCount()) {
            $this->logger->debug('job ['.$job['_id'].'] collected; update status to ['.$status.']', [
                'category' => get_class($this),
                'pm' => $this->process,
            ]);

            $this->db->{$this->scheduler->getEventQueue()}->insertOne([
                'job' => $job['_id'],
                'worker' => $this->id,
                'status' => $status,
                'timestamp' => new UTCDateTime(),
            ]);

            return true;
        }

        $this->logger->debug('job ['.$job['_id'].'] is already collected with status ['.$job['status'].']', [
            'category' => get_class($this),
            'pm' => $this->process,
        ]);

        return false;
    }
370471
public function thenRespond($statusCode, $body)
    {
        $response = ResponseBuilder::create($statusCode)->andBody($body)->build()[1];

        return $this->expectation->setResponse($response);
    }
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();
        }
    }
1130279
public function start()
    {
        if (0 !== $this->oid) {
            throw new StatusError('The context has already been started.');
        }

        list($parent, $child) = Stream\pair();

        switch ($pid = pcntl_fork()) {
            case -1: // Failure
                throw new ForkException('Could not fork process!');

            case 0: // Child
                // @codeCoverageIgnoreStart

                // Create a new event loop in the fork.
                Loop\loop($loop = Loop\create(false));

                $channel = new ChannelledStream($pipe = new DuplexPipe($parent));
                fclose($child);

                $coroutine = new Coroutine($this->execute($channel));
                $coroutine->done();

                try {
                    $loop->run();
                    $code = 0;
                } catch (\Throwable $exception) {
                    $code = 1;
                }

                $pipe->close();

                exit($code);

                // @codeCoverageIgnoreEnd

            default: // Parent
                $this->pid = $pid;
                $this->oid = posix_getpid();
                $this->channel = new ChannelledStream($this->pipe = new DuplexPipe($child));
                fclose($parent);
        }
    }
1232550
protected function message($message, $statusCode) {
		$response =  $this->getAPIResponse(array(
			'message' => $message,
			'statusCode' => $statusCode
		));
		$response->setStatusCode($statusCode);
		return $response;
	}
501064
protected function launchJob($jobID)
        {
            $pid = pcntl_fork();
            if ($pid == -1) {
                error_log('Could not launch new job, exiting');
                echo 'Could not launch new job, exiting';
                return false;
            } else if ($pid) {
                $this->currentJobs[$pid] = $jobID;
                if (isset($this->signalQueue[$pid])) {
                    $this->childSignalHandler(SIGCHLD, $pid, $this->signalQueue[$pid]);
                    unset($this->signalQueue[$pid]);
                }
            } else {
                $exitStatus = 0; //Error code if you need to or whatever
                exit($exitStatus);
            }
            return true;
        }
807596
public function runNow($code)
    {
        if (!Mage::getStoreConfig('system/cron/enableRunNow')) {
            Mage::throwException("'Run now' disabled by configuration (system/cron/enableRunNow)");
        }

        $schedule = Mage::getModel('cron/schedule')/* @var $schedule Aoe_Scheduler_Model_Schedule */
            ->setJobCode($code)
            ->setScheduledReason(Aoe_Scheduler_Model_Schedule::REASON_RUNNOW_API)
            ->runNow(false) // without trying to lock the job
            ->save();

        return $schedule->getData();
    }
1188146
def job_started(self, job, queue):
        
        job.hmset(start=str(datetime.utcnow()), status=STATUSES.RUNNING)
        job.tries.hincrby(1)
        self.log(self.job_started_message(job, queue))
        if hasattr(job, 'on_started'):
            job.on_started(queue)
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);
        }
    }
686915
public function set_status($status, $message = null) {
        $this->status = $status;
        $this->message = is_null($message) ? $this->message : $message;
        $this->timeend = time();
    }
629632
@Override
    public void start(final Infrastructure infra) {
        try {
            final OutputQuartzHelper outputQuartzHelper = new OutputQuartzHelper();
            final JobDetail jobDetail = outputQuartzHelper.getJobDetail(outputInvoker);
            final Trigger trigger = outputQuartzHelper.getCronTrigger(cronExpression);
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();
        } catch (final SchedulerException se) {
            LOGGER.error("Error occurred while starting the cron scheduler : " + se.getMessage(), se);
        }
    }
1091019
public function setStatusCode(int $statusCode, string $statusText = null)
    {
        $this->statusCode = $statusCode;

        if ($statusText === null && isset(ResponseHeaders::$statusTexts[$statusCode])) {
            $this->statusText = ResponseHeaders::$statusTexts[$statusCode];
        } else {
            $this->statusText = $statusText;
        }
    }
1198644
protected function writeStatus(Job $job, $status, $type)
    {
        $this->output->writeln(sprintf(
            "<{$type}>[%s][%s] %s</{$type}> %s",
            date('Y-m-d H:i:s'),
            $job->getJobId(),
            str_pad("{$status}:", 11), $job->getName()
        ));
    }
676617
public function restart()
    {
        $workersArgs = $this->ResqueStatus->getWorkers();

        $this->params['all'] = true;
        $this->stop();

        $this->out('<info>' . __d('cake_resque', 'Restarting workers') . '</info>');
        if (!empty($workersArgs)) {
            $debug = $this->params['debug'];
            $this->debug(__d('cake_resque', 'Found ' . count($workersArgs) . ' workers to restart'));

            foreach ($workersArgs as $workerArgs) {
                $workerArgs['debug'] = $debug;
                if (isset($workerArgs['type']) && $workerArgs['type'] === 'scheduler') {
                    $this->startScheduler($workerArgs);
                } else {
                    $this->start($workerArgs);
                }
            }
            $this->out('');
        } else {
            $this->out('<warning>' . __d('cake_resque', 'No active workers found, will start brand new worker') . '</warning>');
            $this->start();
        }
    }