我必须设置一个 Python 脚本,该脚本应该始终启动并运行,并且应该负责按确定的时间表调用多个函数。 我正在考虑以下方法,它利用库
pycron
和 threading
,假设 func1
、func2
和 func3
是在其他地方定义的 Python 函数。
我的目标是完成以下目标:
(1) 在特定时间运行不同的功能(使用类似cron的计划); (2) 如果需要,使这些功能重叠(=同时运行)成为可能; (3) 避免在上一次运行未完成的情况下再次启动相同的功能
import pycron
from threading import Thread
from custom_modules import func1, func2, func3
t1 = Thread(target=func1)
t2 = Thread(target=func2)
t3 = Thread(target=func3)
while True:
if not t1.is_alive() and pycron.is_now('*/15 * * * *'): # True every 15th minute
t1.start()
time.sleep(60)
if not t2.is_alive() and pycron.is_now('30 22 * * *'): # True at 22:30 every day
t2.start()
time.sleep(60)
if not t3.is_alive() and pycron.is_now('0 0 * * SUN'): # True at midnight on every Sunday
t3.start()
time.sleep(60)
else:
time.sleep(1)
我不确定这种方法是否合理,尤其是对于上面提到的目标(3)。
你怎么看?