我正在运行下面的代码作为示例,其中该函数获取数据并清理它并每五分钟显示一次结果。
import schedule
import time
def job():
print("I'm working...")
schedule.every(5).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
我现在遇到的问题是,当函数运行时,需要几秒钟才能完成所有操作。例如,如果代码在上午 9:00 运行,则需要 2-5 秒才能完成任务。因此,下一次代码将在 9:05:05 秒运行。
有没有一种解决方案可以帮助我每 5 分钟运行一次该函数,即使需要一些时间才能完成该函数中的任务?我希望该函数分别在上午 9:00、上午 9:05 和上午 9:10 准确运行。
按照计划文档中提到的方式运行另一个线程:https://schedule.readthedocs.io/en/stable/
时间表不考虑作业功能执行所需的时间。为了保证稳定的执行计划,您需要将长时间运行的作业移出主线程(调度程序运行的地方)。请参阅并行执行以获取示例实现。
我再次从文档中复制:
import threading
import time
import schedule
def job():
print("I'm running on thread %s" % threading.current_thread())
def run_threaded(job_func):
job_thread = threading.Thread(target=job_func)
job_thread.start()
schedule.every(10).seconds.do(run_threaded, job)
schedule.every(10).seconds.do(run_threaded, job)
schedule.every(10).seconds.do(run_threaded, job)
schedule.every(10).seconds.do(run_threaded, job)
schedule.every(10).seconds.do(run_threaded, job)
while 1:
schedule.run_pending()
time.sleep(1)
import schedule
import time
from datetime import datetime
def my_job():
if datetime.now().minute % 5 == 0:
print("I'm working...", datetime.now())
time.sleep(1)
print("I'm ending...", datetime.now())
schedule.every(1).minutes.at(":30").do(my_job)
while True:
schedule.run_pending()
time.sleep(1)