本文整理汇总了Python中apscheduler.schedulers.background.BackgroundScheduler方法的典型用法代码示例。如果您正苦于以下问题:Python background.BackgroundScheduler方法的具体用法?Python background.BackgroundScheduler怎么用?Python background.BackgroundScheduler使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类apscheduler.schedulers.background
的用法示例。
在下文中一共展示了background.BackgroundScheduler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: background_schedule
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def background_schedule():
from apscheduler.schedulers.background import BackgroundScheduler
def tick():
print('Tick! The time is: %s' % datetime.now())
scheduler = BackgroundScheduler()
scheduler.add_job(tick, 'interval', seconds=3)
scheduler.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
# This is here to simulate application activity (which keeps the main thread alive).
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
# Not strictly necessary if daemonic mode is enabled but should be done if possible
scheduler.shutdown()
示例2: main
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def main():
"""Main method for running all sources."""
scheduler = BackgroundScheduler()
scheduler.start()
Log.i("{} source(s) detected!".format(len(sources.__all__)))
job_id = 1
for source in sources.__all__:
status = run(source) # initial run source.
if status:
# register a scheduler for running periodically. (only for active source)
scheduler.add_job(run, "interval",
minutes=source().cycle, id=str(job_id),
args=(source, ))
Log.i("Successfully add a new job")
job_id += 1
while True:
time.sleep(60) # sleep 1 mintue for running scheduler normally.
scheduler.shutdown()
示例3: main
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def main():
logging.info('Loggrove-Monitor running...')
print('Loggrove-Monitor running...')
make_logfile_thread = threading.Thread(target=make_logfiles, daemon=True) # 每60s 获取主机日志及监控项
make_logfile_thread.start()
send_alert_thread = threading.Thread(target=send_alert, daemon=True) # 消费报警队列,进行告警
send_alert_thread.start()
monitor_report_thread = threading.Thread(target=monitor_report, daemon=True) # 消费日志统计队列,上报给loggrove
monitor_report_thread.start()
scheduler = BackgroundScheduler()
scheduler.add_job(monitor_basic, 'cron', minute='*/1', max_instances=8) # 监控、统计、检查
scheduler.start()
while send_alert_thread.is_alive() and make_logfile_thread.is_alive() and monitor_report_thread.is_alive():
time.sleep(5)
logging.info('Loggrove-Monitor exit...')
print('Loggrove-Monitor exit...')
示例4: __init__
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def __init__(self):
self.__running_tasks = []
self.aps_scheduler = BackgroundScheduler()
# task listener
def task_listener_add(event):
if event.job_id not in self.__running_tasks:
self.__running_tasks.append(event.job_id)
def task_listener_remove(event):
if event.job_id in self.__running_tasks:
self.__running_tasks.remove(event.job_id)
self.aps_scheduler.add_listener(task_listener_add, EVENT_JOB_SUBMITTED)
self.aps_scheduler.add_listener(task_listener_remove, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
# configure all tasks
self.__sonarr_update_task()
self.__radarr_update_task()
self.__cache_cleanup_task()
self.update_configurable_tasks()
self.aps_scheduler.start()
示例5: __init__
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def __init__(self, profile):
self._logger = logging.getLogger(__name__)
self.q = Queue.Queue()
self.profile = profile
self.notifiers = []
if 'gmail_address' in profile and 'gmail_password' in profile:
self.notifiers.append(self.NotificationClient(
self.handle_email_notifications, None))
else:
self._logger.warning('gmail_address or gmail_password not set ' +
'in profile, Gmail notifier will not be used')
sched = BackgroundScheduler(timezone="UTC", daemon=True)
sched.start()
sched.add_job(self.gather, 'interval', seconds=30)
atexit.register(lambda: sched.shutdown(wait=False))
示例6: __init__
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def __init__(self, datastore_dir, threat_max, timezone):
global _scheduler_
self.timezone = timezone
lock = threading.Lock()
with lock:
if not _scheduler_:
jobstores = {
'default': SQLAlchemyJobStore(url='sqlite:///{}/scheduler.sqlite'.format(datastore_dir)),
}
executors = {
'default': ThreadPoolExecutor(threat_max),
}
job_defaults = {
'coalesce': False,
'max_instances': 1
}
_scheduler_ = BackgroundScheduler(
jobstores=jobstores, executors=executors,
job_defaults=job_defaults, timezone=timezone
)
_scheduler_.start()
示例7: setup_runtime
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def setup_runtime(uconfig):
from bot.duel_links_runtime import DuelLinkRunTime
from bot import logger
from bot.providers import get_provider
os.makedirs(uconfig.get('locations', 'log'), exist_ok=True)
setup_logging()
scheduler = BackgroundScheduler()
dlRuntime = DuelLinkRunTime(uconfig, scheduler)
dlRuntime.stop = False # Need to Ensure that it runs
scheduler.start()
try:
dlRuntime.set_provider(get_provider(uconfig.get('bot', 'provider'))(scheduler, uconfig, dlRuntime))
except Exception as e:
logger.critical("Could not get a provider, take a look at your config file")
logger.critical(e)
logger.debug(traceback.format_exc())
sys.exit(1)
try:
dlRuntime.get_provider().sleep_factor = uconfig.getint('bot', 'sleep_factor')
except Exception as e:
logger.critical("Could not set sleep factor, take a look at your config file")
logger.critical(e)
sys.exit(1)
return dlRuntime
示例8: get_scheduler
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def get_scheduler(store_path=None, log_file=None):
if store_path is None:
store_path = r'jobstore.sqlite'
if log_file is None:
log_file = r'logger.log'
scheduler = BackgroundScheduler({'apscheduler.timezone': 'Asia/Shanghai'})
jobstores = {
'default': SQLAlchemyJobStore(url='sqlite:///{0}'.format(store_path))
}
executors = {
'default': ThreadPoolExecutor(20),
'processpool': ProcessPoolExecutor(5)
}
job_defaults = {
'coalesce': False,
'max_instances': 1
}
scheduler.configure(jobstores=jobstores, executors=executors)
# 事件记录
scheduler.add_listener(
lambda event: event_listener(event, scheduler),
EVENT_JOB_EXECUTED | EVENT_JOB_ERROR | EVENT_JOB_ADDED | EVENT_JOB_SUBMITTED | EVENT_JOB_REMOVED
)
# 日志定制
scheduler._logger = modify_logger(scheduler._logger, log_file=log_file)
return scheduler
示例9: init
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def init():
if not ScheduleManager.base_scheduler:
ScheduleManager.base_scheduler = BackgroundScheduler(daemon=True)
ScheduleManager.base_scheduler.start()
示例10: initialize
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def initialize():
log.info("Initializing clean-up task")
scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(cleanup_database, 'interval', hours=12)
示例11: __init__
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def __init__(self, clist_user_name, clist_api_key, mount_point, bot, fallback):
self.clist_user_name = clist_user_name
self.clist_api_key = clist_api_key
self.bot = bot
self.ong = None
self.upc = None
self.mount_point = mount_point
self.utility = ContestUtility(mount_point)
self.jobstores = {
'default': SQLAlchemyJobStore(url='sqlite:///' + mount_point + 'coders1.db')
}
self.schedule = BackgroundScheduler(jobstores=self.jobstores)
self.schedule.start()
self.conv_handler = ConversationHandler(
entry_points=[CommandHandler('upcoming', self.upcoming)],
allow_reentry=True,
states={
SCHED: [CallbackQueryHandler(self.remind, pattern=r"^[0-9]*$")]
},
fallbacks=[fallback]
)
self.conv_handler1 = ConversationHandler(
entry_points=[CommandHandler('dontRemindMe', self.removeRemind)],
allow_reentry=True,
states={
REMNOTI: [CallbackQueryHandler(self.remnoti, pattern=r'^.*notiplz.*$')]
},
fallbacks=[fallback]
)
示例12: scrape_websites
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def scrape_websites(self):
scheduler = BackgroundScheduler()
scheduler.add_job(
self.scheduled_method,
"cron",
day_of_week=self.job_trigger_settings["day_of_job"],
hour=self.job_trigger_settings["hour"],
minute=self.job_trigger_settings["minute"],
second=self.job_trigger_settings["second"],
)
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass
示例13: schedule_job
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def schedule_job(message):
log.info("Received request to schedule the exporter job %s with job_id %s"
% (message['exporter_name'], message['exporter_id']))
metrics_list = message['metrics_list']
for i in metrics_list:
scheduler = BackgroundScheduler()
scheduler.add_jobstore('sqlalchemy', url=CONF.gexporter.scheduler_db_url)
job_id = message['exporter_id']
scheduler.add_job(create_job, args=[i, message["time_interval"],
job_id],
trigger='interval',
minutes=int(message["time_interval"]), id=job_id)
try:
print("Starting scheduler")
scheduler.start()
except Exception as ex:
log.error("last cycle of Scheduler has hit an exception")
"""
try:
while True:
print "In infinite loop"
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()
"""
示例14: run
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def run():
logging.info('Starting scrape service for zone "%s" using key [%s...]'
% (ZONE, AUTH_KEY[0:6]))
update_latest()
scheduler = BackgroundScheduler({'apscheduler.timezone': 'UTC'})
scheduler.add_job(update_latest, 'interval', seconds=60)
scheduler.start()
try:
app.run(host="0.0.0.0", port=SERVICE_PORT, threaded=True)
finally:
scheduler.shutdown()
示例15: __init__
# 需要导入模块: from apscheduler.schedulers import background [as 别名]
# 或者: from apscheduler.schedulers.background import BackgroundScheduler [as 别名]
def __init__(self):
self._logger = logging.getLogger()
config_path = os.path.join(os.path.expanduser('~'), '.strategyease_sdk', 'config', 'scheduler.ini')
self._logger.info('Config path: %s', config_path)
self._config = configparser.RawConfigParser()
self._config.readfp(codecs.open(config_path, encoding="utf_8_sig"), )
self._scheduler = BackgroundScheduler()
self._client = Client(self._logger, **dict(self._config.items('StrategyEase')))