APScheduler

https://github.com/agronholm/apscheduler

高级的python sheduler

 

Advanced Python Scheduler (APScheduler) is a Python library that lets you schedule your Python code to be executed later, either just once or periodically. You can add new jobs or remove old ones on the fly as you please. If you store your jobs in a database, they will also survive scheduler restarts and maintain their state. When the scheduler is restarted, it will then run all the jobs it should have run while it was offline [1].

 

高级的地方包括

job可以持久化。

 

对应低级的 python sheduler, 下面这个不支持持久化。

Schedule

https://www.geeksforgeeks.org/python-schedule-library/

Schedule is in-process scheduler for periodic jobs that use the builder pattern for configuration. Schedule lets you run Python functions (or any other callable) periodically at pre-determined intervals using a simple, human-friendly syntax.

Schedule Library is used to schedule a task at a particular time every day or a particular day of a week. We can also set time in 24 hours format that when a task should run. Basically, Schedule Library matches your systems time to that of scheduled time set by you. Once the scheduled time and system time matches the job function (command function that is scheduled ) is called.

 

# Schedule Library imported
import schedule
import time

# Functions setup
def sudo_placement():
    print("Get ready for Sudo Placement at Geeksforgeeks")

def good_luck():
    print("Good Luck for Test")

def work():
    print("Study and work hard")

def bedtime():
    print("It is bed time go rest")
    
def geeks():
    print("Shaurya says Geeksforgeeks")

# Task scheduling
# After every 10mins geeks() is called.
schedule.every(10).minutes.do(geeks)

# After every hour geeks() is called.
schedule.every().hour.do(geeks)

# Every day at 12am or 00:00 time bedtime() is called.
schedule.every().day.at("00:00").do(bedtime)

# After every 5 to 10mins in between run work()
schedule.every(5).to(10).minutes.do(work)

# Every monday good_luck() is called
schedule.every().monday.do(good_luck)

# Every tuesday at 18:00 sudo_placement() is called
schedule.every().tuesday.at("18:00").do(sudo_placement)

# Loop so that the scheduling task
# keeps on running all time.
while True:

    # Checks whether a scheduled task
    # is pending to run or not
    schedule.run_pending()
    time.sleep(1)

 

 

多种调度器

https://apscheduler.readthedocs.io/en/latest/userguide.html#choosing-the-right-scheduler-job-store-s-executor-s-and-trigger-s

  • BlockingScheduler: use when the scheduler is the only thing running in your process

  • BackgroundScheduler: use when you’re not using any of the frameworks below, and want the scheduler to run in the background inside your application

  • AsyncIOScheduler: use if your application uses the asyncio module

  • GeventScheduler: use if your application uses gevent

  • TornadoScheduler: use if you’re building a Tornado application

  • TwistedScheduler: use if you’re building a Twisted application

  • QtScheduler: use if you’re building a Qt application

 

持久化

可以将job保存到数据库, 下次程序重启, 会从数据库中重新加载job执行。

To pick the appropriate job store, you need to determine whether you need job persistence or not. If you always recreate your jobs at the start of your application, then you can probably go with the default (MemoryJobStore). But if you need your jobs to persist over scheduler restarts or application crashes, then your choice usually boils down to what tools are used in your programming environment. If, however, you are in the position to choose freely, then SQLAlchemyJobStore on a PostgreSQL backend is the recommended choice due to its strong data integrity protection.

 

 

支持JOB CRUD API

https://apscheduler.readthedocs.io/en/latest/userguide.html#adding-jobs

Adding jobs

There are two ways to add jobs to a scheduler:

  1. by calling add_job()

  2. by decorating a function with scheduled_job()

 

Removing jobs

When you remove a job from the scheduler, it is removed from its associated job store and will not be executed anymore. There are two ways to make this happen:

  1. by calling remove_job() with the job’s ID and job store alias

  2. by calling remove() on the Job instance you got from add_job()

 

Removing jobs

When you remove a job from the scheduler, it is removed from its associated job store and will not be executed anymore. There are two ways to make this happen:

  1. by calling remove_job() with the job’s ID and job store alias

  2. by calling remove() on the Job instance you got from add_job()

 

code demo
"""
Demonstrates how to use the asyncio compatible scheduler to schedule a job that executes on 3
second intervals.
"""

from datetime import datetime
import os

from apscheduler.schedulers.asyncio import AsyncIOScheduler

try:
    import asyncio
except ImportError:
    import trollius as asyncio


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = AsyncIOScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    # Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
    try:
        asyncio.get_event_loop().run_forever()
    except (KeyboardInterrupt, SystemExit):
        pass