Reputation: 35
I want to run a function for only n number of seconds after which the function shouldn't run anymore while in the background other functions should continue running. I've tried using the time.time() function with the while loop but other functions in the background doesn't run and I want it such a way that even other functions can be run at the same time. For eg: if 3 functions function A, function B and function C exists. My function A, and B should run continously while Function C should run only for a certain time in the background
Upvotes: 1
Views: 450
Reputation: 3096
my code:
from threading import Thread, Lock
import time
from datetime import datetime, timedelta
s_t = datetime.now()
lock = Lock()
def A():
while True:
lock.acquire()
print('A running time : ', datetime.now() - s_t)
lock.release()
time.sleep(0.5)
def B():
while True:
lock.acquire()
print('B running time : ', datetime.now() - s_t)
print('t_a.is_alive() : ', t_a.is_alive())
print('t_b.is_alive() : ', t_b.is_alive())
print('t_c.is_alive() : ', t_c.is_alive())
lock.release()
time.sleep(0.5)
def C():
while datetime.now() - s_t < timedelta(seconds=10) :
lock.acquire()
print('C running : ', datetime.now() - s_t)
lock.release()
time.sleep(0.5)
t_a = Thread(target=A)
t_a.start()
t_b =Thread(target=B)
t_c =Thread(target=C)
t_b.start()
t_c.start()
output when C
runs for more than 10 seconds :
......
A running time : 0:00:09.508521
B running time : 0:00:09.509433
t_a.is_alive() : True
t_b.is_alive() : True
t_c.is_alive() : True
C running : 0:00:09.509557
A running time : 0:00:10.008677
B running time : 0:00:10.009638
t_a.is_alive() : True
t_b.is_alive() : True
t_c.is_alive() : False
.....
Upvotes: 0
Reputation: 151
use threading and the timeout parameter for join https://docs.python.org/3/library/threading.html#threading.Thread.start
from threading import Thread
import time
def A():
while True:
time.sleep(2)
def B():
while True:
time.sleep(1)
def C():
while True:
time.sleep(1)
t_a = Thread(target=A)
t_a.run()
Thread(target=B).run()
Thread(target=C).run()
t_a.join(timeout=10)
Upvotes: 2