【问题标题】:Running a function indefinitely at specific time of day in Python在 Python 中的特定时间无限期运行函数
【发布时间】:2021-03-03 16:10:50
【问题描述】:

我有一个函数,我需要每天从下午 5 点运行到第二天早上 9 点,然后在下午 5 点重新开始。下面是我的实现:

import datetime as dt
import time 
while True:
    if dt.datetime.now().hour < 9 or dt.datetime.now().hour > 17:
        #some irrelevant function here
        print('Function processing')
        time.sleep(1) 
    else:
        print("Not time yet")
        time.sleep(1)
        continue

上面的代码有效,但我还想在下午 5 点的每个第一个循环和上午 9 点的最后一个循环之后执行一次函数。我的第一直觉是做这样的事情:

def starting(): print("It's 9pm, time to start!")
def ending(): print("It's 5am, time to end")
while True:
    if dt.datetime.now().hour < 9 or dt.datetime.now().hour > 17:
        if #this is the first loop since 5pm:
            starting()
        elif #this is the last loop at 9am:
            ending()
        #some irrelevant function here
        print('Function processing')
        time.sleep(1)
    else:
        print("Not time yet")
        time.sleep(1)
        continue

我不确定这是否是最好的方法,希望能有一些想法。

【问题讨论】:

标签: python loops datetime if-statement while-loop


【解决方案1】:

在你的while循环中,模仿你做过的同样的事情:

#you can call your ending function here
if dt.datetime.now().hour == 17:
    do something

#you can call your starting function here
elif dt.datetime.now().hour == 9:
    do something different

这将根据小时执行操作。

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 2016-04-04
    • 2016-09-20
    • 2017-04-17
    相关资源
    最近更新 更多