[英]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.