繁体   English   中英

在设定的时间后调用 Function 但继续使用 Python 运行程序代码

[英]Call a Function After a Set Time But Continue to Run Code the Program with Python

我想在设定的时间后调用 function,但继续运行 python 程序。 这可能吗?

示例用例:

使用以下代码,我想在 2 天后调用 function happy_birthday 但在此之前不断打印Not your birthday

def happy_birthday():
    print("Happy Birthday")
    exit()

[MISSING CODE THAT CALLS happy_birthday]

while True:
    print("Not your birthday!")

您正在寻找threading.Timer
这会在特定时间后调用一个方法作为线程。

我假设您想在happy_birthday中使用exit()退出程序? 您可以通过将条件(变量run )设置为False来做到这一点。

import threading
import time

run = True


def happy_birthday():
    print("Happy Birthday")
    global run
    run = False


t = threading.Timer(60 * 60 * 24 * 2, happy_birthday)
t.start()  # after 2 day, happy_birthday will be called

while run:
    print("Not your birthday!")
    time.sleep(.1)

Output

Not your birthday!
Not your birthday!
...
Not your birthday!
Happy Birthday

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM