如何在一天中的特定时间 start/stop 一个函数?
How to start/stop a function at specific time of the day?
如果我有一个全天循环的函数,表示为:
def Show()
我怎样才能 运行 它在一天中的特定时间不会 return 任何东西?
在这种情况下说 13:50 到 14:20?
如果我对问题的理解正确,您可以使用 if
语句检查时间:
# import datetime module
from datetime import datetime as dt
# set to time bounds:
lower_bound = dt.time(13, 50)
upper_bound = dt.time(14, 20)
然后只要在函数运行时检查时间即可:
now = dt.now().time()
if lower_bound < now < upper_bound:
pass
if not (lower_boun < now < upper_bond):
Show() #that returns something.
...或者只是将 if 语句放入函数本身
看看这个 question on now()
and this question on comparing time
通过 chepner 和 0x5423 的有用评论改进了答案
schedule
是完成所有这些的优秀模块。它甚至可以在没有太多工作的情况下运行异步。
https://schedule.readthedocs.io/en/stable/
schedule.every(1).hours.at("06:00").do(show).tag('show', 'guest')
然后在特定时间停止计划
schedule.every().day.at("10:30").clear('show')
如果我有一个全天循环的函数,表示为:
def Show()
我怎样才能 运行 它在一天中的特定时间不会 return 任何东西?
在这种情况下说 13:50 到 14:20?
如果我对问题的理解正确,您可以使用 if
语句检查时间:
# import datetime module
from datetime import datetime as dt
# set to time bounds:
lower_bound = dt.time(13, 50)
upper_bound = dt.time(14, 20)
然后只要在函数运行时检查时间即可:
now = dt.now().time()
if lower_bound < now < upper_bound:
pass
if not (lower_boun < now < upper_bond):
Show() #that returns something.
...或者只是将 if 语句放入函数本身
看看这个 question on now()
and this question on comparing time
通过 chepner 和 0x5423 的有用评论改进了答案
schedule
是完成所有这些的优秀模块。它甚至可以在没有太多工作的情况下运行异步。
https://schedule.readthedocs.io/en/stable/
schedule.every(1).hours.at("06:00").do(show).tag('show', 'guest')
然后在特定时间停止计划
schedule.every().day.at("10:30").clear('show')