Activate polling function and register first crontab
555467
def activate_crontab(self):
        
        self._crontab = []
        if hasattr(self, 'CRONTAB'):
            for crontab_spec in self.CRONTAB:
                args = cronjob.parse_crontab(crontab_spec)
                job = cronjob.CronJob()
                if args['_timer'] == 'datetime':
                    job.set_triggers(args['trigger_format'], args['trigger_time'])
                if args['_timer'] == 'crontab':
                    job.set_crontab(args['crontab'])
                if args['action'].startswith('.'):
                    action_name = args['action'][1:]
                    action_ = getattr(self.__class__, action_name)
                else:
                    action_ = args['action']
                job.set_action(action_, *args['args'])
                self._crontab.append(job)
        self.start_poller(30, self.poll_crontab)
1238241
def start_polling(dispatcher, *, loop=None, skip_updates=False, reset_webhook=True,
                  on_startup=None, on_shutdown=None, timeout=20, fast=True):
    
    executor = Executor(dispatcher, skip_updates=skip_updates, loop=loop)
    _setup_callbacks(executor, on_startup, on_shutdown)

    executor.start_polling(reset_webhook=reset_webhook, timeout=timeout, fast=fast)
277480
def run_once(self):
        ''''''

        self._update_projects()
        self._check_task_done()
        self._check_request()
        while self._check_cronjob():
            pass
        self._check_select()
        self._check_delete()
        self._try_dump_cnt()
78221
async function start() {
  try {
    await server.register({ plugin: hapijsStatusMonitor });
    await server.start();
  }
  catch (err) {
    console.log(err);
    process.exit(1);
  }

  console.log('Server running at:', server.info.uri);
}
1345384
function () {
        const cronJobsToStart = _getNamesOfCronJobsToStart();
        if (!cronJobsToStart && _shouldStartCrons() && Shared.isDbConnectionAvailable() === true) {
            return CronJobManagerJob.startListening().then(function () {
                Logger.tag('Cron').info('Cron Job Manager is started. Starting all available cron jobs');
                return Q();
            }, function (err) {
                Logger.tag('Cron').error('Error starting Cron Job Manager ');
                return Q.reject(err);
            });
        } else if (cronJobsToStart && _shouldStartCrons()) {

            Logger.tag('Cron').info('Starting specific cron jobs "' + cronJobsToStart.join(', ') + '"');

            try {
                const cronJobs = Shared.cronModules(cronJobsToStart);
                let promises = [];
                for (let cron of cronJobs) {
                    // Set force run config
                    cron.forceRun = true;
                    promises.push(cron.worker(cron, cron));
                }
                return Q.all(promises)
                    .then(() => process.exit())
                    .catch(() => process.exit(1));
            } catch (err) {
                process.exit(1);
            }
        } else {
            Logger.tag('Cron').warn('Cron Manager is disabled for this environment.');
            return Q();
        }
    }
780173
private function _run(): void
  {
    // The DB and the controller exist
    if ( $this->check() && isset($this->data['type'])){
      if ( !defined('BBN_EXTERNAL_USER_ID') && defined('BBN_EXTERNAL_USER_EMAIL') ){
        define('BBN_EXTERNAL_USER_ID', $this->db->select_one('bbn_users', 'id', ['email' => BBN_EXTERNAL_USER_EMAIL]));
      }
      if ( defined('BBN_EXTERNAL_USER_ID') && class_exists('\\bbn\\appui\\history') ){
        \bbn\appui\history::set_user(BBN_EXTERNAL_USER_ID);
      }
      $type = $this->data['type'];
      // Removing file cache
      clearstatcache();
      // only 2 types: poll or cron
      if ( $type !== 'poll' ){
        $type = 'cron';
      }
      $pid = $this->get_pid_path($this->data);

      // Checking for the presence of the manual files
      if (
        !$this->is_active() ||
        (($type === 'cron') && !$this->is_cron_active()) ||
        (($type === 'poll') && !$this->is_poll_active())
      ){
        // Exiting the script if one is missing
        if ( is_file($pid) ){
          @unlink($pid);
        }
        exit("GETTING OUT of $type BECAUSE one of the manual files is missing");
      }
      // Loooking for a running PID
      if ( is_file($pid) && ($file_content = @file_get_contents($pid)) ){
        $pid_content = explode('|', $file_content);
        if ( $pid_content[1] && file_exists('/proc/'.$pid_content[0]) ){
          // If it's currently running we exit
          exit("There is already a process running with PID ".file_get_contents($pid)." in $pid");
        }
        else{
          // Otherwise we delete the PID file
          echo "DELETING FILEPID AS THE PROCESS IS DEAD ".implode(PHP_EOL, $pid_content).PHP_EOL;
          @unlink($pid);
        }
      }
      // We create the PID file corresponding to the current process
      file_put_contents($pid, getmypid().'|'.time());
      $cron =& $this;
      // Shutdown function, will be always executed, except if the server is stopped
      register_shutdown_function(function() use($cron){
        $data = $cron->get_data();
        $pid = $this->get_pid_path($data);
        $file_content = @file_get_contents($pid);
        // Write the error log if an error is present
        if ( $error = error_get_last() ){
          @file_put_contents($cron->get_error_log_path($data), \bbn\x::get_dump($error));
          if ( defined('BBN_DATA_PATH') && is_dir(BBN_DATA_PATH.'logs') ){
            bbn\x::log([$data, $error], 'cron');
          }
        }
        $ok = true;
        // We check if there is a problem with the PID file (it's only debug it shouldn't be necessary)
        if ( $file_content ){
          echo $file_content.PHP_EOL;
          $pid_content = explode('|', $file_content);
          if ( $pid_content[1] && ($pid_content[0] != getmypid()) ){
            echo 'Different processes: '.$pid_content[0].'/'.getmypid().PHP_EOL;
            $ok = false;
          }
        }
        if ( $ok && isset($data['type']) ){
          // We output the ending time (as all output will be logged in the output file
          echo 'SHUTDOWN '.date('H:i:s');
          // Removing PID file
          if ( is_file($pid) ){
            @unlink($pid);
          }
          // And relaunching the continuous tasks if we are in the poller...
          if ( ($data['type'] === 'poll') && $cron->is_poll_active() ){
            $cron->launch_poll();
          }
          else if ( !array_key_exists('id', $data) && ($data['type'] === 'cron') && $cron->is_cron_active() ){
            $cron->launch_task_system();
          }
        }
      });
      // And here we really do what we have to do
      // Poll case
      if ( $type === 'poll' ){
        $this->poll();
      }
      else if ( $type === 'cron' ){
        if ( array_key_exists('id', $this->data) ){
          echo 'Launching task...';
          $this->run_task($this->data);
        }
        else{
          $this->run_task_system();
        }
      }
    }
  }
741021
function _sync_install_cron_method( array $blog_ids, $current_blog_id = null ) {
            if ( $this->is_registered() ) {
                if ( 1 < count( $blog_ids ) ) {
                    $this->sync_installs( array(), true );
                } else {
                    $this->sync_install( array(), true );
                }
            }
        }
739853
function pollJob(client, jobUuid, cb) {
    var attempts = 0;
    var errors = 0;

    var timeout = 5000;  // 5 seconds
    var limit = 720;     // 1 hour

    var poll = function () {
        client.get('/jobs/' + jobUuid, function (err, req, res, job) {
            attempts++;

            if (err) {
                errors++;
                if (errors >= 5) {
                    return cb(err);
                } else {
                    return setTimeout(poll, timeout);
                }
            }

            if (job && job.execution === 'succeeded') {
                return cb(null, job);
            } else if (job && job.execution === 'failed') {
                return cb(null, job);
            } else if (job && job.execution === 'canceled') {
                return cb(null, job);
            } else if (attempts > limit) {
                return cb(new Error('polling for import job timed out'), job);
            }

            return setTimeout(poll, timeout);
        });
    };

    poll();
}
1100222
def _setup_crontab():
    """"""
    from crontab import CronTab
    #Since CI works out of a virtualenv anyway, the `ci.py` script will be
    #installed in the bin already, so we can call it explicitly.
    command = '/bin/bash -c "source ~/.cron_profile; workon {}; ci.py -cron"'.format(settings.venv)
    user = _get_real_user()
    if args["nolive"]:
        vms("Skipping cron tab configuration because 'nolive' enabled.")
        return
    cron = CronTab(user=user)
    
    #We need to see if the cron has already been created for this command.
    existing = False
    possible = cron.find_comment("pyci_cron")
    if len(list(possible)) > 0:
        if args["rollback"]:
            vms("Removing {} from cron tab.".format(command))
            cron.remove_all(command)
            cron.write()
            db["cron"] = False
            _save_db()
        else:
            existing = True
    
    if not existing and not args["rollback"]:
        job = cron.new(command=command, comment="pyci_cron")
        #Run the cron every minute of every hour every day.
        if args["cronfreq"] == 1:
            vms("New cron tab configured *minutely* for {}".format(command))
            job.setall("* * * * *")
        else:
            vms("New cron tab configured every {} minutes for {}.".format(args["cronfreq"], command))
            job.setall("*/{} * * * *".format(args["cronfreq"]))
        cron.write()
        db["cron"] = True
        _save_db()
795989
def dispatch(self):
        """"""
        parser = argparse.ArgumentParser(description='Run an Inbox server.')

        parser.add_argument('addr', metavar='addr', type=str, help='addr to bind to')
        parser.add_argument('port', metavar='port', type=int, help='port to bind to')

        args = parser.parse_args()

        self.serve(port=args.port, address=args.addr)
764259
function () {
    var self = this;
    if (self._pollsScheduledButNotStarted > 0)
      return;
    ++self._pollsScheduledButNotStarted;
    self._taskQueue.queueTask(function () {
      self._pollMongo();
    });
  }
1003405
def UpdateCronJob(self,
                    cronjob_id,
                    last_run_status=db.Database.unchanged,
                    last_run_time=db.Database.unchanged,
                    current_run_id=db.Database.unchanged,
                    state=db.Database.unchanged,
                    forced_run_requested=db.Database.unchanged,
                    cursor=None):
    """"""
    updates = []
    args = []
    if last_run_status != db.Database.unchanged:
      updates.append("last_run_status=%s")
      args.append(int(last_run_status))
    if last_run_time != db.Database.unchanged:
      updates.append("last_run_time=FROM_UNIXTIME(%s)")
      args.append(mysql_utils.RDFDatetimeToTimestamp(last_run_time))
    if current_run_id != db.Database.unchanged:
      updates.append("current_run_id=%s")
      args.append(db_utils.CronJobRunIDToInt(current_run_id))
    if state != db.Database.unchanged:
      updates.append("state=%s")
      args.append(state.SerializeToString())
    if forced_run_requested != db.Database.unchanged:
      updates.append("forced_run_requested=%s")
      args.append(forced_run_requested)

    if not updates:
      return

    query = "UPDATE cron_jobs SET "
    query += ", ".join(updates)
    query += " WHERE job_id=%s"
    res = cursor.execute(query, args + [cronjob_id])
    if res != 1:
      raise db.UnknownCronJobError("CronJob with id %s not found." % cronjob_id)
1064390
def submit(self, func, *args, **kwargs):
        
        with self._shutdown_lock:
            if self._shutdown:
                raise RuntimeError(
                    'cannot schedule new futures after shutdown')
            if self.in_green_worker:
                return wait(func(*args, **kwargs))
            else:
                future = create_future(self._loop)
                self._put((future, func, args, kwargs))
                return future
585432
function Poll($secs=5)
	{
		$this->conn->fnExecute = false;
		//$this->conn->debug=1;
		if ($secs <= 1) $secs = 1;
		echo "Accumulating statistics, every $secs seconds...\n";flush();
		$arro = $this->PollParameters();
		$cnt = 0;
		set_time_limit(0);
		sleep($secs);
		while (1) {

			$arr = $this->PollParameters();

			$hits   = sprintf('%2.2f',$arr[0]);
			$reads  = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);
			$writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);
			$sess = sprintf('%5d',$arr[3]);

			$load = $this->CPULoad();
			if ($load !== false) {
				$oslabel = 'WS-CPU%';
				$osval = sprintf(" %2.1f  ",(float) $load);
			}else {
				$oslabel = '';
				$osval = '';
			}
			if ($cnt % 10 == 0) echo " Time   ".$oslabel."   Hit%   Sess           Reads/s          Writes/s\n";
			$cnt += 1;
			echo date('H:i:s').'  '.$osval."$hits  $sess $reads $writes\n";
			flush();

			if (connection_aborted()) return;

			sleep($secs);
			$arro = $arr;
		}
	}
890124
def RunOnce(self):
    """"""
    # Start the cron thread if configured to.
    if config.CONFIG["Cron.active"]:

      self.cron_worker = CronWorker()
      self.cron_worker.RunAsync()
221039
def EnableJob(self, job_id, token=None):
    """"""
    job_urn = self.CRON_JOBS_PATH.Add(job_id)
    cron_job = aff4.FACTORY.Open(
        job_urn, mode="rw", aff4_type=CronJob, token=token)
    cron_job.Set(cron_job.Schema.DISABLED(0))
    cron_job.Close()
306058
def loop(self, sleep_time=1, callback=None):
        

        self.log("No supported libraries found: using polling-method.")
        self._running = True
        self.trigger_init()
        self._scan(trigger=False)  # put after the trigger
        if self._warn:
            print("""
You should install a third-party library so I don't eat CPU.
Supported libraries are:
  - pyinotify (Linux)
  - pywin32 (Windows)
  - MacFSEvents (OSX)

Use pip or easy_install and install one of those libraries above.
""")
        while self._running:
            self._scan()
            if isinstance(callback, collections.Callable):
                callback()
            time.sleep(sleep_time)