def initialize(self): """Initialize croniter and related times""" if self.croniter is None: self.time = time.time() self.datetime = datetime.now(dateutil.tz.tzlocal()) self.loop_time = self.loop.time() self.croniter = croniter(self.spec, start_time=self.datetime)
def wrapper(*args, **kwargs): LOGGER.info('timer started: for %(func)s to run every %(crontab_expression)s', { 'func': func, 'crontab_expression': self.crontab_expression }) while True: now = get_current_timestamp() # TODO: remove croniter hack when croniter is fixed # next_run = croniter(self.crontab_expression, now).get_next() ct = croniter(self.crontab_expression, now + DEFAULT_CLIENT_TIMEZONE.utcoffset(datetime.now()).total_seconds()) next_run = ct.get_next(ret_type=float) - DEFAULT_CLIENT_TIMEZONE.utcoffset(datetime.now()).total_seconds() delta = next_run - now LOGGER.info('timer sleep: wake up after %(delta)s seconds', { 'delta': delta }) time.sleep(delta) LOGGER.info('timer woke up') before = time.time() try: func(*args, **kwargs) finally: after = time.time() LOGGER.info('timer work done: in %(elapsed_time)s seconds', { 'elapsed_time': after - before })
def runCron(self, cron: str) -> timedFuncWrap: return self.addTimed( croniter( cron, start_time=datetime.today(), ret_type=datetime, ))
def initialize(self): """Initialize croniter and related times""" if self.croniter is None: self.time = time.time() self.datetime = datetime.now(self.tz) # 返回当前时间,一个float值,根据事件循环的内部时钟。 self.loop_time = self.loop.time() self.croniter = croniter(self.spec, start_time=self.datetime)
def _update_next_trigger_at(self): """ Defines next backup creation time """ base_time = django_timezone.now().replace( tzinfo=pytz.timezone(self.timezone)) self.next_trigger_at = croniter(self.schedule, base_time).get_next(datetime)
def secs_for_next(cron_format: str, tz: tzinfo = None) -> float: now_ts = time.time() # If we have a tz object we'll make now timezone aware, and # if not will set now to be the current timestamp (tz # unaware) # If we have tz, now will be a datetime, if not an integer now = tz and datetime.now(tz) or now_ts cron_it = croniter(cron_format, start_time=now) return cron_it.get_next(float) - now_ts
def secs_for_next(cron_format: str, tz: tzinfo = None) -> float: """Return seconds until next execution given crontab style format.""" now_ts = time.time() # If we have a tz object we'll make now timezone aware, and # if not will set now to be the current timestamp (tz # unaware) # If we have tz, now will be a datetime, if not an integer now = datetime.now(tz) if tz else now_ts cron_it = croniter(cron_format, start_time=now) return cron_it.get_next(float) - now_ts
def cron_string_to_next_datetime(minute="*", hour="*", day_of_month="*", month="*", day_of_week="*"): cron_string = ("%s %s %s %s %s" % (minute or '*', hour or '*', day_of_month or '*', month or '*', day_of_week or '*')) iter = croniter(cron_string, timeutils.utcnow()) return iter.get_next(datetime.datetime)
def cron_string_to_next_datetime(minute="*", hour="*", day_of_month="*", month="*", day_of_week="*", start_time=None): start_time = start_time or timeutils.utcnow() cron_string = ("%s %s %s %s %s" % (_default_if_none(minute, '*'), _default_if_none(hour, '*'), _default_if_none(day_of_month, '*'), _default_if_none(month, '*'), _default_if_none(day_of_week, '*'))) iter = croniter(cron_string, start_time) return iter.get_next(datetime.datetime)
def schedule(self, date_from=None): """Return a croniter schedule if available.""" if not date_from: date_from = datetime.now() try: # Croniter is an optional import from croniter.croniter import croniter except ImportError: raise ImportError("Croniter not available. Please install croniter" " python module via pip or your package manager") return croniter(self.slices.clean_render(), date_from, ret_type=datetime)
def get_next_utc_execution(self): tz = pytz.timezone(self.timezone) if not self.next_execution: base = tz.normalize(datetime.now(tz) - timedelta(minutes=1)) elif self.skip_delayed_jobs_next_time: base = tz.normalize(datetime.now(tz)) else: base = tz.normalize(self.next_execution.replace(tzinfo=pytz.utc)) cron = croniter(self.schedule, base) return cron.get_next(datetime).astimezone(pytz.utc)
def main(): parser = argparse.ArgumentParser() parser.prog = "python -m aiocron" parser.add_argument( "-n", type=int, default=1, help="loop N times. 0 for infinite loop", ) parser.add_argument("crontab", help='quoted crontab. like "* * * * *"') parser.add_argument("command", nargs='+', help="shell command to run") args = parser.parse_args() cron = args.crontab try: croniter(cron) except ValueError: parser.error('Invalid cron format') cmd = args.command loop = asyncio.get_event_loop() def calback(): subprocess.call(cmd) if args.n != 0: cron.n -= 1 if not cron.n: loop.stop() cron = crontab(cron, func=calback) cron.n = args.n cron.start() try: loop.run_forever() except: pass
def cron_string_to_next_datetime(minute="*", hour="*", day_of_month="*", month="*", day_of_week="*", start_time=None): start_time = start_time or timeutils.utcnow() cron_string = ( "%s %s %s %s %s" % (_default_if_none(minute, '*'), _default_if_none(hour, '*'), _default_if_none(day_of_month, '*'), _default_if_none( month, '*'), _default_if_none(day_of_week, '*'))) iter = croniter(cron_string, start_time) return iter.get_next(datetime.datetime)
def wrapper(*args, **kwargs): LOGGER.info('timer started: for %(func)s to run every %(crontab_expression)s', { 'func': func, 'crontab_expression': self.crontab_expression }) while True: now = get_current_timestamp() next = croniter(self.crontab_expression, now).get_next() delta = next - now LOGGER.info('timer sleep: wake up after %(delta)s seconds', { 'delta': delta }) time.sleep(delta) LOGGER.info('timer woke up') before = time.time() try: func(*args, **kwargs) finally: after = time.time() LOGGER.info('timer work done: in %(elapsed_time)s seconds', { 'elapsed_time': after - before })
def update_next_trigger_at(self): base_time = django_timezone.now().replace(tzinfo=pytz.timezone(self.timezone)) self.next_trigger_at = croniter(self.schedule, base_time).get_next(datetime)
def _cron_expr(naive_utc_dt, expr): aware_utc_dt = convert_naive_datetime_to_aware(naive_utc_dt, tzinfo=pytz.utc) local_dt = convert_datetime_to_client_timezone(aware_utc_dt) next_dt = croniter(expr, start_time=local_dt).get_next(ret_type=datetime) return convert_datetime_to_utc_timezone(next_dt)
def get_next_timestamp(self, now=None): now = now or get_current_timestamp() # TODO: remove croniter hack here and in Timer class when croniter is fixed # return croniter(self.crontab_expression, now).get_next(ret_type=float) ct = croniter(self.crontab_expression, now + DEFAULT_CLIENT_TIMEZONE.utcoffset(datetime.now()).total_seconds()) return ct.get_next(ret_type=float) - DEFAULT_CLIENT_TIMEZONE.utcoffset(datetime.now()).total_seconds()
def __init__(self, crontab_expression): croniter(crontab_expression) # validate the expression, throws exception if invalid self.crontab_expression = crontab_expression
def initialize(self): """Initialize croniter and related times""" if self.croniter is None: self.time = time.time() self.loop_time = self.loop.time() self.croniter = croniter(self.spec, start_time=self.time)
def cron(self): if not self.__cron_iter: self.__cron_iter = croniter(str(self), now(self.timezone)) return self.__cron_iter
def update_next_trigger_at(self): tz = pytz.timezone(self.timezone) dt = tz.normalize(django_timezone.now()) self.next_trigger_at = croniter(self.schedule, dt).get_next(datetime)
def get_next_timestamp(self, now=None): now = now or get_current_timestamp() return croniter(self.crontab_expression, now).get_next(ret_type=float)