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.
JavaScript
x
9
1
def happy_birthday():
2
print("Happy Birthday")
3
exit()
4
5
[MISSING CODE THAT CALLS happy_birthday]
6
7
while True:
8
print("Not your birthday!")
9
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
.
JavaScript
1
19
19
1
import threading
2
import time
3
4
run = True
5
6
7
def happy_birthday():
8
print("Happy Birthday")
9
global run
10
run = False
11
12
13
t = threading.Timer(60 * 60 * 24 * 2, happy_birthday)
14
t.start() # after 2 day, happy_birthday will be called
15
16
while run:
17
print("Not your birthday!")
18
time.sleep(.1)
19
Output
JavaScript
1
6
1
Not your birthday!
2
Not your birthday!
3
4
Not your birthday!
5
Happy Birthday
6