コード例 #1
0
    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!")
コード例 #2
0
    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!")
コード例 #3
0
    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.')
コード例 #4
0
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
コード例 #5
0
    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!")
コード例 #6
0
    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!')
コード例 #7
0
ファイル: runapscheduler.py プロジェクト: microlis/moduleD6
    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!")
コード例 #8
0
ファイル: __init__.py プロジェクト: mowgliamu/robotoff
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()
コード例 #9
0
    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!")
コード例 #10
0
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()
コード例 #11
0
    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!")
コード例 #12
0
ファイル: runappsheduler.py プロジェクト: DminGerasimov/D-7
    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!")
コード例 #13
0
ファイル: runapscheduler.py プロジェクト: scrmtl/server
    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!")
コード例 #14
0
    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()
コード例 #15
0
    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()
コード例 #16
0
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
コード例 #17
0
ファイル: run.py プロジェクト: aurdipas/smartva-dhis2
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()
コード例 #18
0
    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()
コード例 #19
0
ファイル: scheduler.py プロジェクト: vasuporov/gym
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
コード例 #20
0
    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()
コード例 #21
0
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
コード例 #22
0
ファイル: startjobs.py プロジェクト: stjordanis/materials
    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!")
コード例 #23
0
ファイル: init_aps_schedule.py プロジェクト: gioh/webdbtool
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()
コード例 #24
0
    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!")
コード例 #25
0
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()
コード例 #26
0
ファイル: mongodb.py プロジェクト: cychenyin/windmill
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
コード例 #27
0
"""

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
コード例 #28
0
"""

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
コード例 #29
0
ファイル: redis_.py プロジェクト: drkmsmithjr/erica
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
コード例 #30
0
ファイル: twse.py プロジェクト: leochung0728/stock
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()
コード例 #31
0
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
コード例 #32
0
ファイル: twse.py プロジェクト: leochung0728/stock
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()
コード例 #33
0
ファイル: apscheduler.py プロジェクト: sealandsigh/reboot9
# -*- 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)
コード例 #34
0
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
コード例 #35
0
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
コード例 #36
0
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
コード例 #37
0
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