def reload(self): for profile in BackupProfileModel.select(): trigger = None job_id = f"{profile.id}" if profile.schedule_mode == "interval": trigger = cron.CronTrigger( hour=f"*/{profile.schedule_interval_hours}", minute=profile.schedule_interval_minutes, ) elif profile.schedule_mode == "fixed": trigger = cron.CronTrigger( hour=profile.schedule_fixed_hour, minute=profile.schedule_fixed_minute, ) if self.get_job(job_id) is not None and trigger is not None: self.reschedule_job(job_id, trigger=trigger) notifier = RestaticNotifications.pick()() notifier.deliver("Restatic Scheduler", "Background scheduler was changed.") logger.debug("Job for profile %s was rescheduled.", profile.name) elif trigger is not None: self.add_job( func=self.create_backup, args=[profile.id], trigger=trigger, id=job_id, misfire_grace_time=180, ) logger.debug("New job for profile %s was added.", profile.name) elif self.get_job(job_id) is not None and trigger is None: self.remove_job(job_id) logger.debug("Job for profile %s was removed.", profile.name)
def reload(self): for profile in BackupProfileModel.select(): trigger = None job_id = f'{profile.id}' if profile.schedule_mode == 'interval': trigger = cron.CronTrigger( hour=f'*/{profile.schedule_interval_hours}', minute=profile.schedule_interval_minutes) elif profile.schedule_mode == 'fixed': trigger = cron.CronTrigger( hour=profile.schedule_fixed_hour, minute=profile.schedule_fixed_minute) if self.get_job(job_id) is not None and trigger is not None: self.reschedule_job(job_id, trigger=trigger) notifier = VortaNotifications.pick()() notifier.deliver('Vorta Scheduler', 'Background scheduler was changed.') logger.debug('Job for profile %s was rescheduled.', profile.name) elif trigger is not None: self.add_job(func=self.create_backup, args=[profile.id], trigger=trigger, id=job_id, misfire_grace_time=180) logger.debug('New job for profile %s was added.', profile.name) elif self.get_job(job_id) is not None and trigger is None: self.remove_job(job_id) logger.debug('Job for profile %s was removed.', profile.name)
def start_e_Ticketing(self): try: print("예약 시작") trigger = OrTrigger([ c.CronTrigger(hour=self.re_hh_txt.text(), minute=self.re_mm_txt.text()) # i.IntervalTrigger(seconds=0.5) ]) self.sched.add_job(self.start_Ticketing2, trigger) self.sched.start() except Exception as e: print('예외 맨', e)
async def _schedule_job(self, user_data: dict): """Schedules a job based on user_data passed""" try: job_id = f"{user_data.get('guild_id')}|{user_data.get('user_id')}" run_time: datetime = user_data.get("unmute_time") if isinstance(run_time, str): run_time = datetime.strptime(run_time, "%Y-%m-%d %H:%M:%S.%f") if run_time is not None and run_time <= datetime.utcnow(): # bumps events in the past a few seconds into the future # to handle events that should have occurred while the bot # was offline run_time = datetime.utcnow() + timedelta(seconds=10) job = self.scheduler.get_job(job_id) if run_time is not None: # the trigger for an job trigger = cron.CronTrigger( year=run_time.year, month=run_time.month, day=run_time.day, hour=run_time.hour, minute=run_time.minute, second=run_time.second, timezone=pytz.utc, ) if job: job.reschedule(trigger=trigger) log.debug(f"Unmute job rescheduled for {run_time.ctime()}") else: self.scheduler.add_job( func=self.auto_unmute, kwargs={ "user_id": user_data.get("user_id"), "guild_id": user_data.get("guild_id") }, trigger=trigger, id=job_id, name=f"Auto-unmute job for {job_id}", ) log.debug(f"Unmute job scheduled for {run_time.ctime()}") else: # runtime is none, delete the job if job: self.scheduler.remove_job(job_id) log.debug(f"Job deleted due to empty run_time {job_id}") except Exception as e: log.error("Error scheduling job:\n" + "".join( traceback.format_exception(type(e), e, e.__traceback__)))
def reload(self): for profile in BackupProfileModel.select(): trigger = None job_id = f'{profile.id}' if profile.schedule_mode == 'interval': if profile.schedule_interval_hours >= 24: days = profile.schedule_interval_hours // 24 leftover_hours = profile.schedule_interval_hours % 24 if leftover_hours == 0: cron_hours = '1' else: cron_hours = f'*/{leftover_hours}' trigger = cron.CronTrigger(day=f'*/{days}', hour=cron_hours, minute=profile.schedule_interval_minutes) else: trigger = cron.CronTrigger(hour=f'*/{profile.schedule_interval_hours}', minute=profile.schedule_interval_minutes) elif profile.schedule_mode == 'fixed': trigger = cron.CronTrigger(hour=profile.schedule_fixed_hour, minute=profile.schedule_fixed_minute) if self.get_job(job_id) is not None and trigger is not None: self.reschedule_job(job_id, trigger=trigger) logger.debug('Job for profile %s was rescheduled.', profile.name) elif trigger is not None: self.add_job( func=self.create_backup, args=[profile.id], trigger=trigger, id=job_id, misfire_grace_time=180 ) logger.debug('New job for profile %s was added.', profile.name) elif self.get_job(job_id) is not None and trigger is None: self.remove_job(job_id) logger.debug('Job for profile %s was removed.', profile.name)
def add_service_jobs(self, func, job_params, jobstore): # проход по циклу всех временных периодов for p in job_params['params']: # выполняем каждый день по умолчанию trigger_period = {'day': '*/1'} # назначаем время старта start_time = { 'hour': job_params.get('start_time')[0:2], 'minute': job_params.get('start_time')[3:5] } trigger_period.update(start_time) if job_params.get( 'type', '' ) == 'summ': # если это задание по суммаризации то меняем период тригера if p.get('unit') == 'day': trigger_period.update(day='*/1') # выполняем каждый день elif p.get('unit') == 'week': trigger_period.update( day_of_week='0') # выполняем каждую неделю elif p.get('unit') == 'month': trigger_period.update(day='1') # выполняем каждый месяц else: trigger_period = { 'hour': '*/1' } # выполняем каждый час по умолчанию tz_moscow = pytz.timezone('Europe/Moscow') trigger = cron.CronTrigger(**trigger_period, timezone=tz_moscow) j_id = job_params.get("id", "") j_name = job_params.get("name", "") j_type = job_params.get("type", "") j_data = p.get("data", "") j_value = p.get("value", "") j_unit = p.get("unit", "") # устанавливаем параметры для задания kwargs = {'id': j_id, 'name': j_name, 'type': j_type} kwargs.update(p) # добавляем временной период self.add_job(func, trigger=trigger, replace_existing=True, jobstore=jobstore, executor='default', kwargs=kwargs, id=f'{j_id}_{j_data}_{j_value}_{j_unit}', name=f'{j_type} {j_data} {j_value} {j_unit}')
async def auto_unmute(self, user_id, guild_id): """Called at a set time to automatically unmute a user""" try: log.debug(f"Running unmute task for {guild_id}/{user_id}") # grab db data to check the user is *actually* due for un-muting guild: discord.Guild = self.bot.get_guild(int(guild_id)) user: discord.Member = guild.get_member(int(user_id)) if not guild or not user: return user_data = await self.bot.get_member_data(guild_id, user.id) # check if user is still muted if not user_data.muted: # user has been un-muted already return unmute_time = user_data.unmute_time if not (unmute_time.hour <= datetime.utcnow().hour and unmute_time.minute <= datetime.utcnow().minute): # the job has run at the wrong time # this can occur if the user was re-muted for a new time, but for some reason _schedule_job didnt reschedule it job = self.scheduler.get_job( f"{user_data.guild_id}|{user_data.user_id}") if job: run_time = user_data.unmute_time if isinstance(run_time, str): run_time = datetime.strptime(user_data.unmute_time, "%Y-%m-%d %H:%M:%S.%f") trigger = cron.CronTrigger( year=run_time.year, month=run_time.month, day=run_time.day, hour=run_time.hour, minute=run_time.minute, second=run_time.second, timezone=pytz.utc, ) job.reschedule(trigger) return log.debug( f"Unmute job rescheduled for {run_time.ctime()}") return # actually unmute await user.remove_roles(await self.get_mute_role(guild)) # remove from db user_data.unmute_time = None user_data.muted = False await self.bot.redis.set(user_data.key, user_data.to_json()) me = guild.get_member(self.bot.user.id) await self.bot.paladinEvents.add_item( Action( actionType=ModActions.unmute, moderator=me, guild=guild, user=user, reason= f"AUTOMATIC ACTION: \nMute scheduled to be removed at `{unmute_time.ctime()}` (UTC)", )) except Exception as e: log.error("Error un-muting:\n" + "".join( traceback.format_exception(type(e), e, e.__traceback__)))
def getcron(self): return cron.CronTrigger()
else: code = {"code": "1"} finally: log.logger.info('finish html') return jsonify(code) def get_port(db_config='root.conf'): config = configparser.ConfigParser() config.read(db_config) host = config['APPRUN']['host'] post = int(config['APPRUN']['port']) ft = config['APPRUN']['time'] return host, post, ft if __name__ == "__main__": host_i, port_i, f_time = get_port() scheduler = BackgroundScheduler() triggers = cron.CronTrigger(day='*/1', hour=f_time, minute='00', second='00') try: scheduler.add_job(ads.main_ad, trigger=triggers, args=[]) # scheduler.add_job(project_ad_function.person_ad_process, trigger='interval', seconds=5, args=[log]) except Exception as e: log.logger.warning(e) scheduler.start() app.run(host=host_i, port=port_i, debug=False)