检测crontab任务数量

@return bool
@throws \InvalidArgumentException
168687
private function checkTaskCount(): bool
    {
        if (! isset($i)) {
            static $i = 0;
        }

        $i++;
        if ($i > TableCrontab::$taskCount) {
            throw new \InvalidArgumentException('The crontab task::' . $i . ' exceeds the threshold::' . TableCrontab::$taskCount);
        }

        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());
    }
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;
	}
635145
public function handle()
    {
        if(config('deploy.cron')) {
            $this->comment("\nCreating cron jobs");
            foreach(config('deploy.cron') as $cronCommand){
                $output = $this->scriptParser->parseFile(
                    'createCronJobs', [
                    'command' => $cronCommand,
                    'base_path' => base_path(),
                    'env' => $this->option('env')
                    ]
                )->run($this);
                
                if(!$output) {
                    return false;
                }
            }
        }
    }
978938
public function getCronCommand()
    {
        $phpBinaryFinder = new PhpExecutableFinder();
        $php = $phpBinaryFinder->find();
        $command = 'cd ' . str_replace(' ', '\ ', GRAV_ROOT) . ';' . $php . ' bin/grav scheduler';

        return "(crontab -l; echo \"* * * * * {$command} 1>> /dev/null 2>&1\") | crontab -";
    }
124920
public function list() : String
    {
        $list = '';

        if( is_file($this->crontabCommands) )
        {
            $jobs  = $this->listArray();
            $list  = '<pre>';
            $list .= '[ID] CRON JOB<br><br>';

            foreach( $jobs as $key => $job )
            {
                $list .= '[' . $key . ']: '. $job . '<br>';
            }

            $list .= '</pre>';
        }

        return $list;
    }
1047413
protected function tryStart()
    {
        // 检查是否达到预定时间
        try {
            if (!$this->testTimer()) {
                return false;
            }
        } catch (\Exception $ex) {
            $this->log('error', 'Job testTimer() error', [
                'error' => $ex->getMessage(),
            ]);

            return false;
        }

        // 上下文中是否保存了前一个任务pid
        if (!$recent_proc_id = $this->getContext(self::KEY_PROC_ID)) {
            return true;
        }

        // 检查进程ID是否真正存在
        if (!posix_kill($recent_proc_id, 0)) {
            $errno = posix_get_last_error();

            if ($errno === 3) {
                return true;
            }

            $this->log('warning', 'Job kill error', [
                'error' => posix_strerror($errno),
            ]);

            return false;
        }

        // 如果上一个任务还没有超时就放弃当前任务
        $recent_proc_time = $this->getContext(self::KEY_PROC_TIME);
        if (time() - $recent_proc_time < $this->timeout) {
            $this->log('notice', 'Job cancel, previous job still run', [
                'previous_proc_id' => $recent_proc_id,
            ]);

            return false;
        }

        // 中止超时任务
        posix_kill($recent_proc_id, SIGKILL);
        $this->log('warning', 'Job killed by timeout', [
            'previous_proc_id' => $recent_proc_id,
        ]);

        return true;
    }
1070879
public function run(): bool
    {
        if ($this->startup) {
            $this->logger->debug('Calling startup callback');
            call_user_func($this->startup, $this);
        }

        $actions = implode(', ', array_keys($this->callbacks));
        $this->logger->info("Component running with callbacks for $actions");
        $this->executor->execute(
            $this->apiFactory,
            $this->input,
            $this->callbacks,
            $this->error
        );

        if ($this->shutdown) {
            $this->logger->debug('Calling shutdown callback');
            call_user_func($this->shutdown, $this);
        }

        return true;
    }
894084
public function fetchAll() {
        $crontab = $this->_exec('crontab -l');
        $crontab = trim($crontab);
        if (preg_match('/no crontab for/', $crontab)) {
            return null;
        } else {
            $cronjobs = explode("\n", $crontab);
            return $cronjobs;
        }
    }
1321753
public function parseFromFile(Crontab $crontab, $filename)
    {
        if (!is_readable($filename)) {
            throw new \InvalidArgumentException('File '.$filename.' is not readable.');
        }

        $file = file_get_contents($filename);
        foreach ($this->parseString($file) as $element) {
            $crontab->addItem($element);
        }

        return $this;
    }
1060500
public function actionLs($params = false){
        /**
         * @var $cron Crontab
         */

        if(false == $params) {

            $cron = $this->module->get($this->module->nameComponent);
            $jobs = $cron->getJobs();

            foreach ($jobs as $index=>$job) {
                /**
                 * @var $job Cronjob
                 */
                if($job->getGroup() == $this->module->cronGroup)
                echo '['.$index.'] '. $this->ansiFormat($job->getJobCommand(), Console::FG_CYAN);
            }
        } elseif($params == 'a' || $params == 'al') {
            echo shell_exec('crontab -l') . PHP_EOL;
        }

    }
599575
public function exec(): bool
    {
        /* @var $sqlStmt \PDOStatement */
        $sqlStmt = $this->getConnection()->prepare($this->getQuery());

        if ($sqlStmt === false) {
            return $this->execFails($sqlStmt, ErrorType::CONNECTION_ERROR);
        }

        // Bind input
        foreach ($this->bindedValues as /* @var $i int */
                 $i => $bindedValue) {
            $type = $this->getPDOType($bindedValue);

            if ($type === false) {
                throw new \Exception('Invalid type of binded value at position ' . ($i + 1) . '.');
            }

            $bindParamsResult = $sqlStmt->bindValue($i + 1, $bindedValue, $type);

            if ($bindParamsResult === false) {
                return $this->execFails($sqlStmt, ErrorType::BINDING_ERROR);
            }
        }

        // Exec query
        $result = $sqlStmt->execute();

        if ($result == false) {
            return $this->execFails($sqlStmt, ErrorType::STATEMENT_ERROR);
        }

        $this->result = new MPDOResult($sqlStmt);

        $sqlStmt->closeCursor();

        return true;
    }
1216358
public function save()
    {
        if (!empty($this->log)) {

            if (!$this->check($this->config)) {
                // 检测日志写入权限
                return false;
            }

            if (empty($this->config['level'])) {
                // 获取全部日志
                $log = $this->log;
                if (!$this->config['debug'] && isset($log['debug'])) {
                    unset($log['debug']);
                }
            } else {
                // 记录允许级别
                $log = [];
                foreach ($this->config['level'] as $level) {
                    if (isset($this->log[$level])) {
                        $log[$level] = $this->log[$level];
                    }
                }
            }

            $result = $this->driver->save($log);
            if ($result) {
                $this->log = [];
            }

            return $result;
        }

        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;
    }
109474
private function checkTaskQueue(bool $reStart): bool
    {
        if (! isset($i)) {
            static $i = 0;
        }

        if ($reStart) {
            $i = 0;
        }

        $i++;

        if ($i > TableCrontab::$taskQueue) {
            throw new \InvalidArgumentException('The crontab task-queue::' . $i . ' exceeds the threshold::' . TableCrontab::$taskQueue);
        }

        return true;
    }
1230979
protected function _initAction()
    {
        if (!Mage::getStoreConfigFlag('system/cron/enable')) {
            $this->_getSession()->addNotice($this->__('Scheduler is disabled in configuration (system/cron/enable). No schedules will be executed.'));
        } else {
            $this->checkHeartbeat();
        }

        // check configuration
        if (Mage::getStoreConfig('system/cron/schedule_generate_every') > Mage::getStoreConfig('system/cron/schedule_ahead_for')) {
            $this->_getSession()->addError($this->__('Configuration problem. "Generate Schedules Every" is higher than "Schedule Ahead for". Please check your <a href="%s">configuration settings</a>.', $this->getUrl('adminhtml/system_config/edit', array('section' => 'system')) . '#system_cron'));
        }

        // Check the cron is being run as the configured user and whether or not to show the message
        $this->_checkCronUser();

        return $this->loadLayout()
            ->_setActiveMenu('system')
            ->_addBreadcrumb($this->__('System'), $this->__('System'))
            ->_addBreadcrumb($this->__('Scheduler'), $this->__('Scheduler'))
            ->_title($this->__('System'))
            ->_title($this->__('Scheduler'));
    }
1010155
protected function createCrontabDirectoryIfNotExists()
    {
        if( ! is_dir($crontabDirectory = pathinfo($this->crontabCommands, PATHINFO_DIRNAME)) )
        {
            Filesystem::createFolder($crontabDirectory);
        }
    }