def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") # добавляем работу нашему задачнику scheduler.add_job( weekly_newsletter_to_subscribers, trigger=CronTrigger(day_of_week='mon', hour="08", minute="30"), id="weekly_newsletter_to_subscribers", # уникальный айди max_instances=1, replace_existing=True, ) logger.info("Added job 'weekly_newsletter_to_subscribers'.") scheduler.add_job( delete_old_weekly_newsletter_to_subscribers(), trigger=CronTrigger( day_of_week="tue", hour="00", minute="00" ), # Каждую неделю будут удаляться старые задачи, которые либо не удалось выполнить, либо уже выполнять не надо. id="delete_old_weekly_newsletter_to_subscribers(", max_instances=1, replace_existing=True, ) logger.info( "Added weekly job: 'delete_old_weekly_newsletter_to_subscribers'." ) try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!")
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( my_job, trigger=CronTrigger(second="00"), # Midnight everyday id="my_job", # The `id` assigned to each job MUST be unique max_instances=1, replace_existing=True, ) logger.info("Added job 'my_job'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger(hour="00", minute="00"), # Midnight every day id="delete_old_job_executions", max_instances=1, replace_existing=True, ) logger.info("Added weekly job: 'delete_old_job_executions'.") try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!")
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), 'default') scheduler.add_job( update_exporters, trigger=CronTrigger(hour='23', minute='50'), id='update_exporters', max_instances=1, replace_existing=True, ) logger.info("Added job 'update_exporters'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger(day_of_week="mon", hour="00", minute="00"), id='delete_old_job_executions', max_instances=1, replace_existing=True, ) logger.info("Added weekly job 'delete_old_job_executions'.") try: logger.info('Starting scheduler...') scheduler.start() except KeyboardInterrupt: logger.info('Stopping scheduler...') scheduler.shutdown() logger.info('Scheduler shut down successfully.')
def run(): logging.basicConfig(level=logging.DEBUG) scheduler = BlockingScheduler() scheduler.add_jobstore("memory") alarm_time = datetime.now() + timedelta(seconds=1) scheduler.add_job(alarm, "date", run_date=alarm_time, args=[datetime.now()]) alarm_time = datetime.now() + timedelta(seconds=1) scheduler.add_job(alarm, "date", run_date=alarm_time, args=[datetime.now()]) alarm_time = datetime.now() + timedelta(seconds=2) scheduler.add_job(alarm, "date", run_date=alarm_time, args=[datetime.now()]) print("To clear the alarms, delete the example.sqlite file.") print("Press Ctrl+{0} to exit".format("Break" if os.name == "nt" else "C")) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( posts_senders, trigger=CronTrigger(ay_of_week="sun"), id="posts_senders", max_instances=1, replace_existing=True, ) logger.info("Added job 'posts_senders'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week="mon", hour="00", minute="00" ), # Midnight on Monday, before start of the next work week. id="delete_old_job_executions", max_instances=1, replace_existing=True, ) logger.info( "Added weekly job: 'delete_old_job_executions'." ) try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!")
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), 'default') scheduler.add_job( Database.update, trigger=CronTrigger(hour='*'), # Every hour id='Database Update', max_instances=1, replace_existing=True, ) logger.info('Added job \'Database Update\'.') scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week='mon', hour='00', minute='00' ), # Midnight on Monday, before start of the next work week. id='Delete Old Job Executions', max_instances=1, replace_existing=True, ) logger.info( 'Added weekly job: \'delete_old_job_executions\'.' ) try: logger.info('Starting scheduler...') scheduler.start() except KeyboardInterrupt: logger.info('Stopping scheduler...') scheduler.shutdown() logger.info('Scheduler shut down successfully!')
def handle(seld, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( send_weekly_digest, trigger=CronTrigger( day_of_week="mon", hour="00", minute="00" ), id="send_weekly_digest", max_instances=1, replace_existing=True, ) logger.info("Added job 'send_weekly_digest'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week="mon", hour="00", minute="00" ), id="delete_old_job_executions", max_instances=1, replace_existing=True, ) logger.info( "Added weekly job: 'delete_old_job_executions'." ) try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down succesfully!")
def run(): scheduler = BlockingScheduler() scheduler.add_executor(ThreadPoolExecutor(20)) scheduler.add_jobstore(MemoryJobStore()) scheduler.add_job( process_insights, "interval", minutes=2, max_instances=1, jitter=20 ) scheduler.add_job(mark_insights, "interval", minutes=2, max_instances=1, jitter=20) scheduler.add_job(save_facet_metrics, "cron", day="*", hour=1, max_instances=1) scheduler.add_job( download_product_dataset, "cron", day="*", hour="3", max_instances=1 ) scheduler.add_job( functools.partial(refresh_insights, with_deletion=True), "cron", day="*", hour="4", max_instances=1, ) scheduler.add_job( generate_insights, "cron", day="*", hour="4", minute=15, max_instances=1 ) scheduler.add_job( generate_quality_facets, "cron", day="*", hour="5", minute=25, max_instances=1, ) scheduler.add_listener(exception_listener, EVENT_JOB_ERROR) scheduler.start()
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") # добавляем работу нашему задачнику scheduler.add_job( my_job, trigger=CronTrigger(second="*/10"), # Тоже самое что и интервал, но задача тригера таким образом более понятна django id="my_job", # уникальный айди max_instances=1, replace_existing=True, ) logger.info("Added job 'my_job'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger(day_of_week="mon", hour="00", minute="00"), # Каждую неделю будут удаляться старые задачи, которые либо не удалось выполнить, либо уже выполнять не надо. id="delete_old_job_executions", max_instances=1, replace_existing=True, ) logger.info("Added weekly job: 'delete_old_job_executions'.") try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!")
def run(): scheduler = BlockingScheduler() scheduler.add_executor(ThreadPoolExecutor(20)) scheduler.add_jobstore(MemoryJobStore()) scheduler.add_job(process_insights, 'interval', minutes=2, max_instances=1, jitter=20) scheduler.add_job(mark_insights, 'interval', minutes=2, max_instances=1, jitter=20) scheduler.add_job(download_product_dataset, 'cron', day='*', hour='3', max_instances=1) scheduler.add_job(refresh_insights, 'cron', day='*', hour='4', max_instances=1) scheduler.add_job(generate_insights, 'cron', day='*', hour='4', minute=15, max_instances=1) scheduler.add_listener(exception_listener, EVENT_JOB_ERROR) scheduler.start()
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( requestBoxData, trigger=CronTrigger.from_crontab('1 0 * * *'), # trigger=CronTrigger(second="*/10"), # Every 10 seconds id="getBox", max_instances=1, replace_existing=True, ) scheduler.add_job( requestBtcData, trigger=CronTrigger.from_crontab('1 0 * * *'), id="getBtc", max_instances=1, replace_existing=True, ) # scheduler.add_job(requestBtcData, CronTrigger.from_crontab('8 8 * * *', timezone='UTC'), id="getBtcData", replace_existing=True,) # scheduler.add_job(requestBoxData, CronTrigger.from_crontab('10 16 * * *'), id="getBoxData", replace_existing=True,) try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!")
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") # Каждую неделю будут удаляться старые задачи, которые либо не удалось выполнить, либо уже выполнять не надо. scheduler.add_job( delete_old_job_executions, trigger=CronTrigger(day_of_week="mon", hour="00", minute="00"), id="delete_old_job_executions", max_instances=1, replace_existing=True, ) logger.info("Added weekly job: 'delete_old_job_executions'.") scheduler.add_job( weekly_mailing_subscribers, # Каждую неделю в понедельник в 08.00 подписчикам рассылаются письма с недельными новостями trigger=CronTrigger(day_of_week="mon", hour="08", minute="00"), id="weekly_mailing_subscribers", max_instances=1, replace_existing=True, ) logger.info("Added weekly job: 'weekly_mailing_subscribers'.") try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!")
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") ''' scheduler.add_job( my_job, trigger =CronTrigger(second ="*/10"), # Every 10 seconds id="my_job", # The `id` assigned to each job MUST be unique max_instances=1, replace_existing=True, ) logger.info("Added job 'my_job'.") ''' scheduler.add_job( hourly_job, # Every 10 seconds trigger=CronTrigger(day="*", hour="*", minute="10"), id="hourly_job", # The `id` assigned to each job MUST be unique max_instances=1, replace_existing=True, ) logger.info("Added job 'hourly_job'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week="mon", hour="10", minute="00" ), # Midnight on Monday, before start of the next work week. id="delete_old_job_executions", max_instances=1, replace_existing=True, ) logger.info( "Added weekly job: 'delete_old_job_executions'." ) scheduler.add_job( sort_tasks_in_lanes, trigger=CronTrigger( day_of_week="mon", hour="10", minute="00" ), # Midnight on Monday, before start of the next work week. id="sort_tasks_in_lanes", max_instances=1, replace_existing=True, ) logger.info( "Added sort job: 'sort_tasks_in_lanes'." ) try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!")
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job(update_price, trigger=CronTrigger(minute="*/15"), id="my_job", max_instances=1, replace_existing=True) try: scheduler.start() except KeyboardInterrupt: scheduler.shutdown()
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=get_localzone()) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( notify_students, trigger=CronTrigger(minute="*/1"), # Once a minute id="notify_students", # The `id` assigned to each job MUST be unique max_instances=1, replace_existing=True, ) try: scheduler.start() except KeyboardInterrupt: scheduler.shutdown()
def run(*, url: str = f"sqlite:///{pathlib.Path(__file__).name}.sqlite"): logging.basicConfig(level=logging.DEBUG) scheduler = BlockingScheduler() scheduler.add_jobstore("sqlalchemy", url=url) alarm_time = datetime.now() + timedelta(seconds=10) scheduler.add_job(alarm, "date", run_date=alarm_time, args=[datetime.now()]) print("To clear the alarms, delete the example.sqlite file.") print("Press Ctrl+{0} to exit".format("Break" if os.name == "nt" else "C")) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
def _schedule(): """ Background scheduler that runs forever, schedules to (other) SQLite database """ scheduler = BlockingScheduler() url = r'sqlite:///{}'.format(os.path.join(DatabaseConfig.database_dir, 'scheduling.db')) scheduler.add_jobstore('sqlalchemy', url=url) # run every 3 hours HOURS = 3 scheduler.add_job(_run, 'interval', hours=HOURS, args=[False, False], replace_existing=True, id='smartva-dhis2-runner', next_run_time=datetime.now()) logger.info("Scheduling started") scheduler.start()
def handle(self, *args, **options): print("started") scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") shedulers_obj(scheduler) # starter_youtube_parse() # starter() # upload_starter() # # interval_job() try: scheduler.start() except KeyboardInterrupt as e: print(e) scheduler.shutdown()
def main(): ##logger.info("send_sms_reminder") print("send_sms_reminder") # logging.basicConfig() scheduler = BlockingScheduler() scheduler.add_jobstore("sqlalchemy", url=database_url) # Uncomment if we want to remove the jobs # remove_jobs(scheduler) # return add_jobs(scheduler) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week="mon", hour="00", minute="00" ), # Midnight on Monday, before start of the next work week. id="delete_old_job_executions", max_instances=1, replace_existing=True, ) try: scheduler.start() except KeyboardInterrupt: scheduler.shutdown()
class SimpleScheduler(object): scheduler = None def __init__(self, logger, blocking): self._scheduler = BlockingScheduler(logger = logger) if blocking else BackgroundScheduler(logger = logger) print "Created %s" % self._scheduler.__class__.__name__ self._scheduler.add_jobstore('sqlalchemy', url=JOB_STORE_URL) def __getattr__(self, attr): try: return self.__dict__[attr] except KeyError: return getattr(self._scheduler, attr) @classmethod def get_scheduler(cls, logger = None, blocking = False): if cls.scheduler is None: cls.scheduler = SimpleScheduler(logger, blocking) return cls.scheduler
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( fetch_realpython_episodes, trigger="interval", minutes=2, id="The Real Python Podcast", # Each job MUST have a unique ID max_instances=1, # Replaces existing and stops duplicates on restart of the app. replace_existing=True, ) logger.info("Added job: The Real Python Podcast.") scheduler.add_job( fetch_talkpython_episodes, trigger="interval", minutes=2, id="Talk Python Feed", max_instances=1, replace_existing=True, ) logger.info("Added job: Talk Python Feed.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week="mon", hour="00", minute="00" ), # Midnight on Monday, before start of the next work week. id="Delete Old Job Executions", max_instances=1, replace_existing=True, ) logger.info("Added weekly job: Delete Old Job Executions.") try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!")
def init_start_schedule(): scheduler = BlockingScheduler() #scheduler.shutdown(wait=False) url = 'sqlite:////home/apps/dbajob.sqlite' scheduler.add_jobstore('sqlalchemy', url=url, alias='sqlite_js') scheduler.print_jobs() scheduler.start() print 'success!' scheduler.print_jobs()
def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( handle_scheduled_requests, trigger=CronTrigger(minute="*/1"), id="handle_scheduled_requests", max_instances=1, replace_existing=True, ) logger.info("Added job.") try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!")
def main(): config.parse_args() executors = { 'default': ThreadPoolExecutor(10), 'processpool': ProcessPoolExecutor(3) } job_defaults = { 'coalesce': True, 'max_instances': 2, 'misfire_grace_time': 3600 } scheduler = BlockingScheduler(executors=executors, job_defaults=job_defaults, timezone="UTC") # scheduler.add_executor('processpool') scheduler.add_jobstore('sqlalchemy', url=CONF.database.connection) print CONF.database.connection scheduler.add_job(tick, 'interval', seconds=10, id="abcdefg") # scheduler.add_job(tick, 'cron', day='2,7,10,15',id="bill_generation") scheduler.get_job("get_instance_by_hour") or scheduler.add_job( collectInstance, 'cron', hour='*', id="get_instance_by_hour") scheduler.get_job("get_disk_by_hour") or scheduler.add_job( collectDisk, 'cron', hour='*', id="get_disk_by_hour") scheduler.get_job("get_snapshot_by_hour") or scheduler.add_job( collectSnapshot, 'cron', hour='*', id="get_snapshot_by_hour") scheduler.get_job("get_router_by_hour") or scheduler.add_job( collectRouter, 'cron', hour='*', id="get_router_by_hour") scheduler.get_job("get_ip_by_hour") or scheduler.add_job( collectIp, 'cron', hour='*', id="get_ip_by_hour") scheduler.get_job("get_image_by_hour") or scheduler.add_job( collectImage, 'cron', hour='*', id="get_image_by_hour") scheduler.get_job("get_vpn_by_hour") or scheduler.add_job( collectVpn, 'cron', hour='*', id="get_vpn_by_hour") scheduler.get_job("send_data_msg") or scheduler.add_job( send_data_msg, 'cron', minute='*/2', id="send_data_msg") # print help(scheduler) scheduler.start()
You can exit the program, restart it and observe that any previous alarms that have not fired yet are still active. Running the example with the --clear switch will remove any existing alarms. """ from datetime import datetime, timedelta import sys import os from apscheduler.schedulers.blocking import BlockingScheduler def alarm(time): print('Alarm! This alarm was scheduled at %s.' % time) if __name__ == '__main__': scheduler = BlockingScheduler() scheduler.add_jobstore('mongodb', collection='example_jobs') if len(sys.argv) > 1 and sys.argv[1] == '--clear': scheduler.remove_all_jobs() alarm_time = datetime.now() + timedelta(seconds=10) scheduler.add_job(alarm, 'date', run_date=alarm_time, args=[datetime.now()]) print('To clear the alarms, run this example with the --clear argument.') print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
""" from datetime import datetime, timedelta import sys import os from apscheduler.schedulers.blocking import BlockingScheduler def alarm(time): print('Alarm! This alarm was scheduled at %s.' % time) if __name__ == '__main__': scheduler = BlockingScheduler() scheduler.add_jobstore('mongodb', collection='example_jobs') if len(sys.argv) > 1 and sys.argv[1] == '--clear': scheduler.remove_all_jobs() alarm_time = datetime.now() + timedelta(seconds=10) scheduler.add_job(alarm, 'date', run_date=alarm_time, args=[datetime.now()]) print('To clear the alarms, run this example with the --clear argument.') print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
""" from datetime import datetime, timedelta import sys import os from apscheduler.schedulers.blocking import BlockingScheduler def alarm(time): print('Alarm! This alarm was scheduled at %s.' % time) if __name__ == '__main__': scheduler = BlockingScheduler() scheduler.add_jobstore('zookeeper', path='/example_jobs') if len(sys.argv) > 1 and sys.argv[1] == '--clear': scheduler.remove_all_jobs() alarm_time = datetime.now() + timedelta(seconds=10) scheduler.add_job(alarm, 'date', run_date=alarm_time, args=[datetime.now()]) print('To clear the alarms, run this example with the --clear argument.') print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
You can exit the program, restart it and observe that any previous alarms that have not fired yet are still active. Running the example with the --clear switch will remove any existing alarms. """ from datetime import datetime, timedelta import sys import os from apscheduler.schedulers.blocking import BlockingScheduler def alarm(time): print('Alarm! This alarm was scheduled at %s.' % time) if __name__ == '__main__': scheduler = BlockingScheduler() scheduler.add_jobstore('redis', jobs_key='example.jobs', run_times_key='example.run_times') if len(sys.argv) > 1 and sys.argv[1] == '--clear': scheduler.remove_all_jobs() alarm_time = datetime.now() + timedelta(seconds=10) scheduler.add_job(alarm, 'date', run_date=alarm_time, args=[datetime.now()]) print('To clear the alarms, run this example with the --clear argument.') print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore from stock.crawler import twse from apscheduler.executors.pool import ThreadPoolExecutor from apscheduler.schedulers.blocking import BlockingScheduler from datetime import datetime, timedelta scheduler = BlockingScheduler() scheduler.add_jobstore(DjangoJobStore()) # @scheduler.scheduled_job('cron', name='twse', second='*/3') # def twse_job(): # # twse.spider_twse(datetime.today().strftime('%Y%m%d'), datetime.today().strftime('%Y%m%d')).crawler() # print 'my_job is running, Now is %s' % datetime.now().strftime("%Y-%m-%d %H:%M:%S") # scheduler.print_jobs() scheduler.start() scheduler.print_jobs() # job = scheduler.add_job(twse.spider_twse('20170620', '20170620').crawler, 'interval', minutes=5) # scheduler = BlockingScheduler() # scheduler.add_jobstore(DjangoJobStore()) # # scheduler.add_executor(ThreadPoolExecutor(10)) # def my_job(): # print 'my_job is running, Now is %s' % datetime.now().strftime("%Y-%m-%d %H:%M:%S") # scheduler.add_job(my_job, 'cron', second='*/5') # twse.spider_twse('20170621', '20170621').crawler # scheduler.start() # scheduler.print_jobs() # print scheduler.get_jobs()
You can also give it the database URL as an argument. See the SQLAlchemy documentation on how to construct those. """ from datetime import datetime, timedelta import sys import os from apscheduler.schedulers.blocking import BlockingScheduler def alarm(time): print('Alarm! This alarm was scheduled at %s.' % time) if __name__ == '__main__': scheduler = BlockingScheduler() url = sys.argv[1] if len(sys.argv) > 1 else 'sqlite:///example.sqlite' scheduler.add_jobstore('sqlalchemy', url=url) alarm_time = datetime.now() + timedelta(seconds=10) scheduler.add_job(alarm, 'date', run_date=alarm_time, args=[datetime.now()]) print('To clear the alarms, delete the example.sqlite file.') print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore from stock.crawler import twse from apscheduler.executors.pool import ThreadPoolExecutor from apscheduler.schedulers.blocking import BlockingScheduler from datetime import datetime,timedelta scheduler = BlockingScheduler() scheduler.add_jobstore(DjangoJobStore()) # @scheduler.scheduled_job('cron', name='twse', second='*/3') # def twse_job(): # # twse.spider_twse(datetime.today().strftime('%Y%m%d'), datetime.today().strftime('%Y%m%d')).crawler() # print 'my_job is running, Now is %s' % datetime.now().strftime("%Y-%m-%d %H:%M:%S") # scheduler.print_jobs() scheduler.start() scheduler.print_jobs() # job = scheduler.add_job(twse.spider_twse('20170620', '20170620').crawler, 'interval', minutes=5) # scheduler = BlockingScheduler() # scheduler.add_jobstore(DjangoJobStore()) # # scheduler.add_executor(ThreadPoolExecutor(10)) # def my_job(): # print 'my_job is running, Now is %s' % datetime.now().strftime("%Y-%m-%d %H:%M:%S") # scheduler.add_job(my_job, 'cron', second='*/5') # twse.spider_twse('20170621', '20170621').crawler # scheduler.start() # scheduler.print_jobs()
# -*- coding: utf-8 -*- # __author__="jiajun.zhu" # DATE:2020/9/1 from django_apscheduler.jobstores import DjangoJobStore, register_job, register_events from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.schedulers.blocking import BlockingScheduler import datetime from resources.qcloud.cvm import getCvmlist # scheduler = BackgroundScheduler() scheduler = BlockingScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") # @register_job(scheduler, "interval", seconds=3) # def myjob(): # print("myjob is run: {}".format(datetime.datetime.now())) @register_job(scheduler, "interval", seconds=30) def syncQcloud(): getCvmlist() register_events(scheduler)
You can exit the program, restart it and observe that any previous alarms that have not fired yet are still active. Running the example with the --clear switch will remove any existing alarms. """ from datetime import datetime, timedelta import sys import os from apscheduler.schedulers.blocking import BlockingScheduler def alarm(time): print('Alarm! This alarm was scheduled at %s.' % time) if __name__ == '__main__': scheduler = BlockingScheduler() scheduler.add_jobstore('zookeeper', path='/example_jobs') if len(sys.argv) > 1 and sys.argv[1] == '--clear': scheduler.remove_all_jobs() alarm_time = datetime.now() + timedelta(seconds=10) scheduler.add_job(alarm, 'date', run_date=alarm_time, args=[datetime.now()]) print('To clear the alarms, run this example with the --clear argument.') print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
On each run, it adds a new alarm that fires after ten seconds. You can exit the program, restart it and observe that any previous alarms that have not fired yet are still active. You can also give it the database URL as an argument. See the SQLAlchemy documentation on how to construct those. """ from datetime import datetime, timedelta import sys import os from apscheduler.schedulers.blocking import BlockingScheduler def alarm(time): print('Alarm! This alarm was scheduled at %s.' % time) if __name__ == '__main__': scheduler = BlockingScheduler() url = sys.argv[1] if len(sys.argv) > 1 else 'sqlite:///example.sqlite' scheduler.add_jobstore('sqlalchemy', url=url) alarm_time = datetime.now() + timedelta(seconds=10) scheduler.add_job(alarm, 'date', run_date=alarm_time, args=[datetime.now()]) print('To clear the alarms, delete the example.sqlite file.') print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
import os import sys from datetime import datetime, timedelta from apscheduler.schedulers.blocking import BlockingScheduler def alarm(time): print('Alarm! This is alarm was scheduled at %s' % time) if __name__ == '__main__': sched = BlockingScheduler() sched.add_jobstore('redis') if len(sys.argv) > 1 and sys.argv[1] == '--clear': sched.remove_all_jobs() alarm_time = datetime.now() + timedelta(seconds=1) sched.add_job(alarm, 'date', run_date=alarm_time, args=[datetime.now()]) sched.add_job(alarm, 'interval', seconds=1) print('To clear the alarms, run this example with the --clear argument.') print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: sched.start() except (KeyboardInterrupt, SystemExit): pass
You can exit the program, restart it and observe that any previous alarms that have not fired yet are still active. Running the example with the --clear switch will remove any existing alarms. """ from datetime import datetime, timedelta import sys import os from apscheduler.schedulers.blocking import BlockingScheduler def alarm(time): print('Alarm! This alarm was scheduled at %s.' % time) if __name__ == '__main__': scheduler = BlockingScheduler() scheduler.add_jobstore('rethinkdb', database='apscheduler_example') if len(sys.argv) > 1 and sys.argv[1] == '--clear': scheduler.remove_all_jobs() alarm_time = datetime.now() + timedelta(seconds=10) scheduler.add_job(alarm, 'date', run_date=alarm_time, args=[datetime.now()]) print('To clear the alarms, run this example with the --clear argument.') print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass