[英]How do I run a function once a day when other functions run with fixed interval multiple times a day
我有一个使用schedule不断运行的代码,并且代码中有一个地方需要每天运行一次。
代码定义为嵌套的 function。
关于代码的小演示:
def main():
...
...
...
def errorTable():
...
...
file_read.close()
while True:
try:
schedule.run_pending()
schedule.every(1).seconds.do(main)
except:
time.sleep(1)
main
function 大约每 2 分钟执行一次操作。 但是,我希望其中的errorTable
function 每天只运行一次。
由于代码有一定的处理时间,我无法按照datetime运行。 因为可以错过时间。 当我给出一个范围时,代码可以运行不止一次。
除此之外,有没有一种方法可以让我每天运行一次代码?
首先,我在您的代码中看到了一个问题。 似乎每一秒你都会创造一份新工作。 我不认为这是正确的。 尝试这样做:
def main():
...
...
...
def errorTable():
...
...
file_read.close()
schedule.every(1).seconds.do(main)
while True:
schedule.run_pending()
time.sleep(1)
其次,您似乎想要处理异常(如果它们发生在您的函数中)。 时间表文档建议使用包装器:
import functools
def catch_exceptions(cancel_on_failure=False):
def catch_exceptions_decorator(job_func):
@functools.wraps(job_func)
def wrapper(*args, **kwargs):
try:
return job_func(*args, **kwargs)
except:
import traceback
print(traceback.format_exc())
if cancel_on_failure:
return schedule.CancelJob
return wrapper
return catch_exceptions_decorator
关于您的问题,我认为值得提取您希望每天运行一次的 function 并安排它:
@catch_exceptions(cancel_on_failure=False)
def main():
...
...
file_read.close()
@catch_exceptions(cancel_on_failure=False)
def errorTable():
...
...
schedule.every(1).seconds.do(main)
schedule.every(1).day.at("00:00").do(errorTable)
while True:
schedule.run_pending()
time.sleep(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.