Reputation: 39
I want to write a python function that when called should perform some task only for some time.
Example, when this function is called it should poll to the server for let's say 10 seconds and after 10 seconds it should exit.
I thought of doing it this way, but it doesn't seems appropriate. As obviously this function will take more than 10 seconds to do the job.
for i in range (0, 10): # 10 seconds
poll_to_server()
time.sleep(1)
Can you suggest a better way to do this?
Upvotes: 0
Views: 57
Reputation: 11927
If you want to call the function poll_to_server()
repeatedly for 10s, then you can do something like this
import time
t_end = time.time() + 10
while time.time() < t_end:
poll_to_server()
Function time.time
returns the current time in seconds since 1st Jan 1970. The value is in floating point, so you can even use it with sub-second precision. In the beginning the value t_end
is calculated to be "now" + 10 seconds.
The loop will run until the current time exceeds this preset ending time.
Upvotes: 1