def _configure(self, config): # Set general options self._logger = maybe_ref(config.pop('logger', None)) or getLogger('apscheduler.scheduler') self.timezone = astimezone(config.pop('timezone', None)) or get_localzone() # Set the job defaults job_defaults = config.get('job_defaults', {}) self._job_defaults = { 'misfire_grace_time': asint(job_defaults.get('misfire_grace_time', 1)), 'coalesce': asbool(job_defaults.get('coalesce', True)), 'max_instances': asint(job_defaults.get('max_instances', 1)) } # Configure executors self._executors.clear() for alias, value in six.iteritems(config.get('executors', {})): if isinstance(value, BaseExecutor): self.add_executor(value, alias) elif isinstance(value, MutableMapping): executor_class = value.pop('class', None) plugin = value.pop('type', None) if plugin: executor = self._create_plugin_instance('executor', plugin, value) elif executor_class: cls = maybe_ref(executor_class) executor = cls(**value) else: raise ValueError( 'Cannot create executor "%s" -- either "type" or "class" must be defined' % alias) self.add_executor(executor, alias) else: raise TypeError( "Expected executor instance or dict for executors['%s'], got %s instead" % (alias, value.__class__.__name__)) # Configure job stores self._jobstores.clear() for alias, value in six.iteritems(config.get('jobstores', {})): if isinstance(value, BaseJobStore): self.add_jobstore(value, alias) elif isinstance(value, MutableMapping): jobstore_class = value.pop('class', None) plugin = value.pop('type', None) if plugin: jobstore = self._create_plugin_instance('jobstore', plugin, value) elif jobstore_class: cls = maybe_ref(jobstore_class) jobstore = cls(**value) else: raise ValueError( 'Cannot create job store "%s" -- either "type" or "class" must be ' 'defined' % alias) self.add_jobstore(jobstore, alias) else: raise TypeError( "Expected job store instance or dict for jobstores['%s'], got %s instead" % (alias, value.__class__.__name__))
def __init__(self, year=None, month=None, day=None, week=None, day_of_week=None, hour=None, minute=None, second=None, start_date=None, end_date=None, timezone=None): if timezone: self.timezone = astimezone(timezone) elif start_date and start_date.tzinfo: self.timezone = start_date.tzinfo elif end_date and end_date.tzinfo: self.timezone = end_date.tzinfo else: self.timezone = get_localzone() self.start_date = convert_to_datetime(start_date, self.timezone, 'start_date') self.end_date = convert_to_datetime(end_date, self.timezone, 'end_date') values = dict((key, value) for (key, value) in six.iteritems(locals()) if key in self.FIELD_NAMES and value is not None) self.fields = [] assign_defaults = False for field_name in self.FIELD_NAMES: if field_name in values: exprs = values.pop(field_name) is_default = False assign_defaults = not values elif assign_defaults: exprs = DEFAULT_VALUES[field_name] is_default = True else: exprs = '*' is_default = True field_class = self.FIELDS_MAP[field_name] field = field_class(field_name, exprs, is_default) self.fields.append(field)
def _add_job_to_scheduler(self, trigger): trigger_type_ref = trigger['type'] trigger_type = TIMER_TRIGGER_TYPES[trigger_type_ref] try: jsonschema.validate(trigger['parameters'], trigger_type['parameters_schema']) except jsonschema.ValidationError as e: LOG.error('Exception scheduling timer: %s, %s', trigger['parameters'], e, exc_info=True) raise # Or should we just return? time_spec = trigger['parameters'] time_zone = aps_utils.astimezone(trigger['parameters'].get('timezone')) time_type = None if trigger_type['name'] == 'st2.IntervalTimer': unit = time_spec.get('unit', None) value = time_spec.get('delta', None) time_type = IntervalTrigger(**{unit: value, 'timezone': time_zone}) elif trigger_type['name'] == 'st2.DateTimer': # Raises an exception if date string isn't a valid one. dat = date_parser.parse(time_spec.get('date', None)) time_type = DateTrigger(dat, timezone=time_zone) elif trigger_type['name'] == 'st2.CronTimer': cron = time_spec.copy() cron['timezone'] = time_zone time_type = CronTrigger(**cron) if hasattr(time_type, 'run_date') and datetime.now(tzutc()) > time_type.run_date: LOG.warning('Not scheduling expired timer: %s : %s', trigger['parameters'], time_type.run_date) else: self._add_job(trigger, time_type)
def __init__(self, weeks=0, days=0, hours=0, minutes=0, seconds=0, start_date=None, end_date=None, timezone=None): self.interval = timedelta(weeks=weeks, days=days, hours=hours, minutes=minutes, seconds=seconds) self.interval_length = timedelta_seconds(self.interval) if self.interval_length == 0: self.interval = timedelta(seconds=1) self.interval_length = 1 if timezone: self.timezone = astimezone(timezone) elif start_date and start_date.tzinfo: self.timezone = start_date.tzinfo elif end_date and end_date.tzinfo: self.timezone = end_date.tzinfo else: self.timezone = get_localzone() start_date = start_date or (datetime.now(self.timezone) + self.interval) self.start_date = convert_to_datetime(start_date, self.timezone, 'start_date') self.end_date = convert_to_datetime(end_date, self.timezone, 'end_date')
def __init__(self, year=None, month=None, day=None, week=None, day_of_week=None, hour=None, minute=None, second=None, start_date=None, end_date=None, timezone=None): if timezone: self.timezone = astimezone(timezone) elif isinstance(start_date, datetime) and start_date.tzinfo: self.timezone = start_date.tzinfo elif isinstance(end_date, datetime) and end_date.tzinfo: self.timezone = end_date.tzinfo else: self.timezone = get_localzone() self.start_date = convert_to_datetime(start_date, self.timezone, 'start_date') self.end_date = convert_to_datetime(end_date, self.timezone, 'end_date') values = dict((key, value) for (key, value) in six.iteritems(locals()) if key in self.FIELD_NAMES and value is not None) self.fields = [] assign_defaults = False for field_name in self.FIELD_NAMES: if field_name in values: exprs = values.pop(field_name) is_default = False assign_defaults = not values elif assign_defaults: exprs = DEFAULT_VALUES[field_name] is_default = True else: exprs = '*' is_default = True field_class = self.FIELDS_MAP[field_name] field = field_class(field_name, exprs, is_default) self.fields.append(field)
def __init__(self, *, years: int = 0, months: int = 0, weeks: int = 0, days: int = 0, hour: int = 0, minute: int = 0, second: int = 0, start_date: date = None, end_date: date = None, timezone=None) -> None: self.years = years self.months = months self.weeks = weeks self.days = days self.time = time(hour, minute, second) self.start_date = start_date self.end_date = end_date self.timezone = astimezone(timezone) if self.years == self.months == self.weeks == self.days == 0: raise ValueError('interval must be at least 1 day long') if self.start_date and self.end_date and self.start_date > self.end_date: raise ValueError('end_date cannot be earlier than start_date')
def __init__(self, year=None, month=None, day=None, week=None, day_of_week=None, hour=None, minute=None, second=None, start_date=None, end_date=None, timezone=None, offset=None): if timezone: self.timezone = astimezone(timezone) elif isinstance(start_date, datetime) and start_date.tzinfo: self.timezone = start_date.tzinfo elif isinstance(end_date, datetime) and end_date.tzinfo: self.timezone = end_date.tzinfo else: self.timezone = get_localzone() self.start_date = convert_to_datetime(start_date, self.timezone, 'start_date') self.end_date = convert_to_datetime(end_date, self.timezone, 'end_date') if offset is None: self.offset = timedelta(seconds=0) elif isinstance(offset, timedelta): self.offset = offset elif isinstance(offset, six.integer_types): self.offset = timedelta(seconds=offset) else: try: self.offset = timedelta(seconds=int(offset)) except: raise TypeError('Invalid offset: {0!r}'.format(offset)) values = dict((key, value) for (key, value) in six.iteritems(locals()) if key in self.FIELD_NAMES and value is not None) self.fields = [] assign_defaults = False for field_name in self.FIELD_NAMES: if field_name in values: exprs = values.pop(field_name) is_default = False assign_defaults = not values elif assign_defaults: exprs = DEFAULT_VALUES[field_name] is_default = True else: exprs = '*' is_default = True field_class = self.FIELDS_MAP[field_name] field = field_class(field_name, exprs, is_default) self.fields.append(field)
def __setstate__(self, state): if state.get('version', 1) > 1: raise ValueError( 'Got serialized data for version %s of %s, but only version 1 can be handled' % (state['version'], self.__class__.__name__)) self.years, self.months, self.weeks, self.days = state['interval'] self.time = state['time'] self.start_date = state['start_date'] self.end_date = state['end_date'] self.timezone = astimezone(state['timezone'])
def __init__(self, messagelist, hours=0, minutes=0, timezone=None): self.messagelist = messagelist self.interval = timedelta(hours=hours, minutes=minutes) self.interval_length = timedelta_seconds(self.interval) if self.interval_length == 0: self.interval = timedelta(minutes=60) self.interval_length = 1 if timezone: self.timezone = astimezone(timezone) else: self.timezone = get_localzone()
def check_tz(self): from tzlocal import get_localzone try: # APScheduler 3.x from apscheduler.util import astimezone except ImportError: # https://github.com/ralphwetzel/theonionbox/issues/31 # APScheduler 2.x # import six from pytz import timezone, utc from datetime import tzinfo # copied here from apscheduler/util.py (version 3.4) # copyright Alex Grönholm # https://github.com/agronholm/apscheduler def astimezone(obj): """ Interprets an object as a timezone. :rtype: tzinfo """ # if isinstance(obj, six.string_types): if isinstance(obj, (str, unicode)): return timezone(obj) if isinstance(obj, tzinfo): if not hasattr(obj, 'localize') or not hasattr( obj, 'normalize'): raise TypeError( 'Only timezones from the pytz library are supported' ) if obj.zone == 'local': raise ValueError( 'Unable to determine the name of the local timezone -- you must explicitly ' 'specify the name of the local timezone. Please refrain from using timezones like ' 'EST to prevent problems with daylight saving time. Instead, use a locale based ' 'timezone name (such as Europe/Helsinki).') return obj if obj is not None: raise TypeError('Expected tzinfo, got %s instead' % obj.__class__.__name__) tz = get_localzone() try: res = astimezone(tz) except ValueError as ve: return False return True
def _add_job_to_scheduler(self, trigger): trigger_type_ref = trigger["type"] trigger_type = TIMER_TRIGGER_TYPES[trigger_type_ref] try: util_schema.validate( instance=trigger["parameters"], schema=trigger_type["parameters_schema"], cls=util_schema.CustomValidator, use_default=True, allow_default_none=True, ) except jsonschema.ValidationError as e: LOG.error( "Exception scheduling timer: %s, %s", trigger["parameters"], e, exc_info=True, ) raise # Or should we just return? time_spec = trigger["parameters"] time_zone = aps_utils.astimezone(trigger["parameters"].get("timezone")) time_type = None if trigger_type["name"] == "st2.IntervalTimer": unit = time_spec.get("unit", None) value = time_spec.get("delta", None) time_type = IntervalTrigger(**{unit: value, "timezone": time_zone}) elif trigger_type["name"] == "st2.DateTimer": # Raises an exception if date string isn't a valid one. dat = date_parser.parse(time_spec.get("date", None)) time_type = DateTrigger(dat, timezone=time_zone) elif trigger_type["name"] == "st2.CronTimer": cron = time_spec.copy() cron["timezone"] = time_zone time_type = CronTrigger(**cron) utc_now = date_utils.get_datetime_utc_now() if hasattr(time_type, "run_date") and utc_now > time_type.run_date: LOG.warning( "Not scheduling expired timer: %s : %s", trigger["parameters"], time_type.run_date, ) else: self._add_job(trigger, time_type) return time_type
def get_rescheduler(): timer = BlockingScheduler() time_spec = { 'seconds': cfg.CONF.scheduler.rescheduling_interval, 'timezone': aps_utils.astimezone('UTC') } timer.add_job(recover_delayed_executions, trigger=IntervalTrigger(**time_spec), max_instances=1, misfire_grace_time=60, next_run_time=date_utils.get_datetime_utc_now(), replace_existing=True) return timer
def __init__(self, weeks=0, days=0, hours=0, minutes=0, seconds=0, start_date=None, end_date=None, timezone=None): self.interval = timedelta(weeks=weeks, days=days, hours=hours, minutes=minutes, seconds=seconds) self.interval_length = timedelta_seconds(self.interval) if self.interval_length == 0: self.interval = timedelta(seconds=1) self.interval_length = 1 if timezone: self.timezone = astimezone(timezone) elif start_date and start_date.tzinfo: self.timezone = start_date.tzinfo elif end_date and end_date.tzinfo: self.timezone = end_date.tzinfo else: self.timezone = get_localzone() start_date = start_date or (datetime.now(self.timezone) + self.interval) self.start_date = convert_to_ware_datetime(start_date, self.timezone, 'start_date') self.end_date = convert_to_ware_datetime(end_date, self.timezone, 'end_date')
def _add_job_to_scheduler(self, trigger): trigger_type_ref = trigger['type'] trigger_type = TIMER_TRIGGER_TYPES[trigger_type_ref] try: util_schema.validate(instance=trigger['parameters'], schema=trigger_type['parameters_schema'], cls=util_schema.CustomValidator, use_default=True, allow_default_none=True) except jsonschema.ValidationError as e: LOG.error('Exception scheduling timer: %s, %s', trigger['parameters'], e, exc_info=True) raise # Or should we just return? time_spec = trigger['parameters'] time_zone = aps_utils.astimezone(trigger['parameters'].get('timezone')) time_type = None if trigger_type['name'] == 'st2.IntervalTimer': unit = time_spec.get('unit', None) value = time_spec.get('delta', None) time_type = IntervalTrigger(**{unit: value, 'timezone': time_zone}) elif trigger_type['name'] == 'st2.DateTimer': # Raises an exception if date string isn't a valid one. dat = date_parser.parse(time_spec.get('date', None)) time_type = DateTrigger(dat, timezone=time_zone) elif trigger_type['name'] == 'st2.CronTimer': cron = time_spec.copy() cron['timezone'] = time_zone time_type = CronTrigger(**cron) utc_now = date_utils.get_datetime_utc_now() if hasattr(time_type, 'run_date') and utc_now > time_type.run_date: LOG.warning('Not scheduling expired timer: %s : %s', trigger['parameters'], time_type.run_date) else: self._add_job(trigger, time_type) return time_type
def test_str(self): value = astimezone('Europe/Helsinki') assert isinstance(value, tzinfo)
def __init__(self, run_date=None, timezone=None): timezone = astimezone(timezone) or get_localzone() if run_date is not None: self.run_date = convert_to_datetime(run_date, timezone, 'run_date') else: self.run_date = datetime.now(timezone)
def test_none(self): assert astimezone(None) is None
def test_tz(self): tz = pytz.timezone('Europe/Helsinki') value = astimezone(tz) assert tz is value
def __init__(self, run_date=None, timezone=None): timezone = astimezone(timezone) or get_localzone() self.run_date = convert_to_ware_datetime(run_date or datetime.now(), timezone, 'run_date')
def __init__(self, run_date=None, timezone=None): timezone = astimezone(timezone) or get_localzone() self.run_date = convert_to_datetime(run_date or datetime.now(), timezone, 'run_date')