Skip to content
Advertisement

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

I’m wanting to call a function after a set time, but continue to run the python program. Is this possible?

Example use case:

With the following code, I want to call the function happy_birthday after 2 days but continually print Not your birthday until then.

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

[MISSING CODE THAT CALLS happy_birthday]

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

Advertisement

Answer

Your are looking for threading.Timer.
This calls after a specific time a method as thread.

I assume you want to exit the program with exit() in happy_birthday? You can do this by setting the condition (the variable run) to 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
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement