Check cron jobs exists

@return bool Success
342050
public function checkCronJobsExists() {
		if ($this->isOsWindows()) {
			return true;
		}

		$apacheUser = $this->getWebSrvUser();
		if (empty($apacheUser)) {
			return false;
		}

		$cronjobsList = $this->_modelConfigInstaller->getListCronJobsCreation();
		if (empty($cronjobsList)) {
			return true;
		}

		$output = [];
		$exitCode = -1;
		$cmd = 'crontab -u ' . $apacheUser . ' -l 2>/dev/null';
		exec($cmd, $output, $exitCode);
		if ($exitCode !== 0) {
			return false;
		}

		if (empty($output)) {
			return false;
		}

		foreach ($cronjobsList as $cmd => $time) {
			if (empty($cmd)) {
				continue;
			}

			if (count(preg_grep('/^[^#]+' . preg_quote($cmd, '/') . '$/', $output)) == 0) {
				return false;
			}
		}

		return true;
	}
563804
private function jobHasAlreadyBeenRun($jobCode)
    {
        $currentRunningJob = $this->cronCollection->create()
            ->addFieldToFilter('job_code', $jobCode)
            ->addFieldToFilter('status', 'running')
            ->setPageSize(1);

        if ($currentRunningJob->getSize()) {
            $jobOfSameTypeAndScheduledAtDateAlreadyExecuted =  $this->cronCollection->create()
                ->addFieldToFilter('job_code', $jobCode)
                ->addFieldToFilter('scheduled_at', $currentRunningJob->getFirstItem()->getScheduledAt())
                ->addFieldToFilter('status', ['in' => ['success', 'failed']]);

            return ($jobOfSameTypeAndScheduledAtDateAlreadyExecuted->getSize()) ? true : false;
        }

        return false;
    }
1365998
private function is_cron_on( $name ) {
            $this->_logger->entrance( $name );

            /**
             * @var object $cron_data
             */
            $cron_data = $this->get_cron_data( $name );

            return ( ! is_null( $cron_data ) && true === $cron_data->on );
        }
1005887
protected function pushJobs() : bool
    {
        // Skip if no jobs currently in queue
        if (empty($this->jobQueues)) {
            return true;
        }

        // Run trough list of (idle) workers and check if there is a job in queue the worker can handle
        foreach ($this->workerStates as $workerId => $workerState) {
            if ($workerState !== Worker::WORKER_STATE_IDLE) {
                continue;
            }
            $jobData = $this->getJobFromQueue($workerId);
            if (empty($jobData)) {
                continue;
            }
            try {
                $this->workerStats[$workerId]++;
                $this->workerJobMap[$workerId] = $jobData['job_id'];
                $this->workerJobSocket->send($jobData['job_name'], \ZMQ::MODE_SNDMORE);
                $this->workerJobSocket->send($jobData['job_id'], \ZMQ::MODE_SNDMORE);
                $this->workerJobSocket->send($workerId, \ZMQ::MODE_SNDMORE);
                $this->workerJobSocket->send($jobData['payload']);
            } catch (\ZMQException $e) {
                $this->logger->error('Error sending job to worker: ' . $e->getMessage());
            }
        }

        return true;
    }
590392
public function exists(): bool
    {
        $key = $this->getStorageKey();

        return $key && $this->getFlexDirectory()->getStorage()->hasKey($key);
    }
884394
public function isCronConfigured()
    {
        $r1From = new \DateTime('-' . $this->checkingCronPeriod);
        $r1To = new \DateTime('+' . $this->checkingCronPeriod);

        $r2From = new \DateTime('- 1 hour');
        $r2To = new \DateTime();

        $format = \Espo\Core\Utils\DateTime::$systemDateTimeFormat;

        $selectParams = [
            'select' => ['id'],
            'leftJoins' => ['scheduledJob'],
            'whereClause' => [
                'OR' => [
                    [
                        ['executedAt>=' => $r2From->format($format)] ,
                        ['executedAt<=' => $r2To->format($format)],
                    ],
                    [
                        ['executeTime>=' => $r1From->format($format)],
                        ['executeTime<='=> $r1To->format($format)],
                        'scheduledJob.job' => 'Dummy'
                    ]
                ]
            ]
        ];


        return !!$this->getEntityManager()->getRepository('Job')->findOne($selectParams);
    }
703716
public function enqueueIn()
    {
        $this->out('<info>' . __d('cake_resque', 'Scheduling a job') . '</info>');
        if (count($this->args) !== 4) {
            $this->err('<error>' . __d('cake_resque', 'Wrong number of arguments') . '</error>');
            $this->out(__d('cake_resque', 'Usage : enqueueIn <seconds> <queue> <jobclass> <comma-separated-args>'), 2);

            return false;
        }

        $result = CakeResque::enqueueIn($this->args[0], $this->args[1], $this->args[2], explode(',', $this->args[3]), (isset($this->args[4]) ? (bool)$this->args[4] : false));

        $this->out('<success>' . __d('cake_resque', 'Succesfully scheduled Job #{0}', $result) . '</success>');

        $this->out('');
    }
300376
public function checkRunningJobs()
    {
        $maxJobRuntime = intval(Mage::getStoreConfig(self::XML_PATH_MAX_JOB_RUNTIME));

        if ($maxJobRuntime) {
            foreach ($this->getAllRunningSchedules(gethostname()) as $schedule) { /* @var $schedule Aoe_Scheduler_Model_Schedule */
                // checking if the job isn't running too long
                if ($schedule->isAlive()) {
                    if ($schedule->getDuration() > $maxJobRuntime * 60 && !$schedule->getKillRequest()) {
                        $schedule->requestKill(null, 'Kill requested because job exceeded the max job runtime of ' . $maxJobRuntime . ' minutes.');
                    }
                }
            }
        }

        // fallback (where process cannot be checked or if one of the servers disappeared)
        // if a task wasn't seen for some time it will be marked as error
        $markAsErrorAfter = intval(Mage::getStoreConfig(self::XML_PATH_MARK_AS_ERROR));
        $maxAge = time() - min($markAsErrorAfter, 5) * 60;
        if ($markAsErrorAfter) {
            $schedules = Mage::getModel('cron/schedule')->getCollection()/* @var $schedules Mage_Cron_Model_Resource_Schedule_Collection */
            ->addFieldToFilter('status', Aoe_Scheduler_Model_Schedule::STATUS_RUNNING)
                ->addFieldToFilter('last_seen', array('lt' => strftime('%Y-%m-%d %H:%M:00', $maxAge)))
                ->load();

            foreach ($schedules as $schedule) { /* @var $schedule Aoe_Scheduler_Model_Schedule */
                // check one more time
                if ($schedule->isAlive() !== true) {
                    $schedule->markAsDisappeared(sprintf('Host "%s" has not been available for a while now to update the status of this task and the task is not reporting back by itself', $schedule->getHost()));
                    $schedule->save();
                }
            }
        }

        // clean up "running"(!?) tasks that have never been seen (for whatever reason) and have been scheduled before maxAge
        // by robinfritze. @see https://github.com/AOEpeople/Aoe_Scheduler/issues/40#issuecomment-67749476
        $schedules = Mage::getModel('cron/schedule')->getCollection() /* @var $schedules Mage_Cron_Model_Resource_Schedule_Collection */
            ->addFieldToFilter('status', Aoe_Scheduler_Model_Schedule::STATUS_RUNNING)
            ->addFieldToFilter('last_seen', array('null' => true))
            ->addFieldToFilter('host', array('null' => true))
            ->addFieldToFilter('pid', array('null' => true))
            ->addFieldToFilter('scheduled_at', array('lt' => strftime('%Y-%m-%d %H:%M:00', $maxAge)))
            ->load();

        foreach ($schedules->getIterator() as $schedule) { /* @var $schedule Aoe_Scheduler_Model_Schedule */
            $schedule->setLastSeen(strftime('%Y-%m-%d %H:%M:%S', time()));
            $schedule->markAsDisappeared(sprintf('Process "%s" (id: %s) cannot be found anymore', $schedule->getJobCode(), $schedule->getId()));
        }

    }
128454
public function cron() {
        global $CFG;

        if (!$this->enabled() or !$this->cron_autocheck_enabled()) {
            $this->cron_mtrace('Automatic check for available updates not enabled, skipping.');
            return;
        }

        $now = $this->cron_current_timestamp();

        if ($this->cron_has_fresh_fetch($now)) {
            $this->cron_mtrace('Recently fetched info about available updates is still fresh enough, skipping.');
            return;
        }

        if ($this->cron_has_outdated_fetch($now)) {
            $this->cron_mtrace('Outdated or missing info about available updates, forced fetching ... ', '');
            $this->cron_execute();
            return;
        }

        $offset = $this->cron_execution_offset();
        $start = mktime(1, 0, 0, date('n', $now), date('j', $now), date('Y', $now)); // 01:00 AM today local time
        if ($now > $start + $offset) {
            $this->cron_mtrace('Regular daily check for available updates ... ', '');
            $this->cron_execute();
            return;
        }
    }
676458
public function work()
    {
        if (!$this->connect()) {
            $this->logger()->alert(sprintf('Worker unable to connect, exiting'));
            $this->dispatchEvent('Worker.job.connectionFailed');

            return false;
        }

        $jobClass = $this->engine->getJobClass();
        $time = microtime(true);
        while ($this->running) {
            if (is_int($this->maxRuntime) && $this->runtime >= $this->maxRuntime) {
                $this->logger()->debug('Max runtime reached, exiting');
                $this->dispatchEvent('Worker.maxRuntime');
                break;
            } elseif (is_int($this->maxIterations) && $this->iterations >= $this->maxIterations) {
                $this->logger()->debug('Max iterations reached, exiting');
                $this->dispatchEvent('Worker.maxIterations');
                break;
            }

            $this->runtime += microtime(true) - $time;
            $time = microtime(true);
            $this->iterations++;
            $item = $this->engine->pop($this->queue);
            $this->dispatchEvent('Worker.job.seen', ['item' => $item]);
            if (empty($item)) {
                $this->dispatchEvent('Worker.job.empty');
                sleep($this->interval);
                continue;
            }

            $success = false;
            $job = new $jobClass($item, $this->engine);
            if (!is_callable($item['class'])) {
                $this->logger()->alert('Invalid callable for job. Rejecting job from queue.');
                $job->reject();
                $this->dispatchEvent('Worker.job.invalid', ['job' => $job]);
                continue;
            }

            $this->dispatchEvent('Worker.job.start', ['job' => $job]);

            try {
                $success = $this->perform($item, $job);
            } catch (Exception $e) {
                $this->dispatchEvent('Worker.job.exception', [
                    'job' => $job,
                    'exception' => $e,
                ]);
            }

            if ($success) {
                $job->acknowledge();
                $this->dispatchEvent('Worker.job.success', ['job' => $job]);
                continue;
            }

            $this->logger()->info('Failed. Releasing job to queue');
            $job->release();
            $this->dispatchEvent('Worker.job.failure', ['job' => $job]);
        }

        return true;
    }
420197
private function writeCronFile()
    {
        if (empty($this->cronFile)) {
            return false;
        }

        if (!is_file($this->cronFile)) {
            return false;
        }

        if (!is_writable($this->cronFile)) {
            return false;
        }

        return file_put_contents($this->cronFile, $this->generateCron());
    }
349283
public function updateCron(EdgarEzCron $cron): bool
    {
        try {
            $this->getEntityManager()->persist($cron);
            $this->getEntityManager()->flush();
        } catch (ORMException $e) {
            return false;
        }

        return true;
    }
516913
public function run()
    {
        // check if cron instances is defined
        if (!isset($this->configs['instances']) || !Any::isArray($this->configs['instances'])) {
            return null;
        }

        // get timestamp
        $time = time();
        $log = [];

        // each every one instance
        foreach ($this->configs['instances'] as $callback => $delay) {
            if (((int)$this->configs['log'][$callback] + $delay) <= $time) {
                // prepare cron initializing
                list($class, $method) = explode('::', $callback);
                if (class_exists($class) && method_exists($class, $method)) {
                    // make static callback
                    forward_static_call([$class, $method]);
                    $log[] = $callback;
                }
                // update log information
                $this->configs['log'][$callback] = $time + $delay;
            }
        }

        // write updated configs
        App::$Properties->writeConfig('Cron', $this->configs);
        return $log;
    }
1081951
function exists()
    {
        $path = $this->filePath;
        $rc = isset( $this->metaData['mtime'] );
        eZDebugSetting::writeDebug( 'kernel-clustering', "fs::exists( '$path' ): " . ( $rc ? 'true' :'false' ), __METHOD__ );
        return $rc;
    }
286403
def _setup_server():
    
    if args["setup"] or args["install"]:
        #If the cron has been configured, it means that the server has been
        #setup. We also perform some checks of the configuration file and the
        #existence of the virtualenv.
        if not _check_global_settings() or not _check_virtualenv():
            return False

        _cron_profile()
        if "cron" in db and not db["cron"]:
            _setup_crontab()

    if args["rollback"]:
        _setup_crontab()
311410
public function cron_worker() {
		if ( $this->is_worker_locked() ) {
			return;
		}

		$this->start_time = time();

		$this->lock_worker();

		while ( ! $this->time_exceeded() && ! $this->memory_exceeded() ) {
			if ( ! $this->worker->process() ) {
				break;
			}
		}

		$this->unlock_worker();
	}
1905
protected function cron_has_fresh_fetch($now) {
        $recent = $this->get_last_timefetched();

        if (empty($recent)) {
            return false;
        }

        if ($now < $recent) {
            $this->cron_mtrace('The most recent fetch is reported to be in the future, this is weird!');
            return true;
        }

        if ($now - $recent > 24 * HOURSECS) {
            return false;
        }

        return true;
    }