如何使用apscheduler精确地每一小时执行一个Python函数,而不考虑程序运行的开始时间

1 人关注

我有一个函数,使用 threading 模块,每小时执行一次。但是我遇到了一些问题。

即,该功能在几个小时后就不运行了,比如10-12小时后(这个时间是变化的)。

def update_df():
    df = pd.read_sql(sql_query, connections['DB2'])
    threading.Timer(60*60*1, update_df).start()
update_df()

Questions:

  • What is best practice, to implement this function such that it should run for every IST hour(not on system time)?
  • Why threading module haven't worked properly (Is there any built-in module to do same job)?
  • Edit-1:

  • Question-1 is sovled
  • Question-2 need more visibility
  • python
    python-3.x
    multithreading
    multiprocessing
    apscheduler
    Python coder
    Python coder
    发布于 2019-08-28
    2 个回答
    shaik moeed
    shaik moeed
    发布于 2019-08-28
    已采纳
    0 人赞同

    延伸一下@Harley的回答。

    你需要使用 trigger='cron' ,而不是 'interval' 来执行每小时一次。

    Document

    间隔 :当你想在固定的小时/分钟/秒后运行一个函数时,应该使用这个方法,而不考虑日/月/年。 日/月/年。

    cron : 当你想在某一天/月/年的某一小时/分钟/秒运行一个函数时,应该使用这个方法。

    from apscheduler.schedulers.background import BackgroundScheduler
    scheduler = BackgroundScheduler()
    scheduler.configure(timezone='Asia/Kolkata')
    scheduler.add_job(method, trigger='cron', hour='*') # Execute every hour independent of execution time(i.e., 1:00:00, 2:00:00, so on..)
    scheduler.add_job(method_1, 'interval', minutes=30) # Execute on every 30 minutes depends program execution time
    scheduler.start()
    

    To stop scheduler, use .remove_all_jobs()

    Ex: scheduler.remove_all_jobs()
        
    AzamAbbasi
    AzamAbbasi
    发布于 2019-08-28
    0 人赞同

    你可以使用python apscheduler。

    from apscheduler.schedulers.background import BackgroundScheduler
    scheduler = BackgroundScheduler()
    scheduler.configure(timezone='subcontinent/city')
    scheduler.add_job(method-1, 'interval', seconds=10)
    scheduler.add_job(method-2, 'interval', minutes=30)
    scheduler.add_job(method-3, 'interval', hours=1)