簡體   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