Python Forum
Is there a way to not terminate a running thread in python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Is there a way to not terminate a running thread in python (/thread-26522.html)



Is there a way to not terminate a running thread in python - Contra_Boy - May-04-2020

Hi All,
I have a use case where i am executing my script for a set duration. I wanted to know if there is a way to not terminate a running thread and keep on running for the set duration ex. 10 seconds?
My script is running fine but it creates a new thread as soon as the it receives the response for the previous http request. Any pointers will be helpful. Thanks!!


RE: Is there a way to not terminate a running thread in python - SheeppOSU - May-04-2020

There are a couple ways, both of which use the time library. First you'll need to import time. The first method is time.sleep(seconds), which is very simple, but sometimes you may need to do something else to run code while waiting. Here's some example code of the other method.
import time

timeStamp = time.time() #Records a number measured in epoch time
waitTime = 10

while time.time() - timeStamp < waitTime:
    #Run code here
Hope this helps


RE: Is there a way to not terminate a running thread in python - Contra_Boy - May-05-2020

Thanks i a doing something similar but instead using time.process_time() and then running the threads through a loop. Is there a way to get the average of all the requests. I am able to get the response time per execution as below. But is there a way to sum all of these and get the average?

Response:
Thread 0
Thread 1
request: 1 Status: 200OK ResponseTime: 0.003963258999999941
request: 0 Status: 200OK ResponseTime: 0.005142219999999975
Thread 0
Thread 1
request: 0 Status: 200OK ResponseTime: 0.004329180999999904
request: 1 Status: 200OK ResponseTime: 0.004248067999999994


RE: Is there a way to not terminate a running thread in python - SheeppOSU - May-05-2020

You can save the response times in a list, then find the average
responseTimesList = [1.2, 0.7, 0.9, 1.4] #These would be appended to the list somewhere in your code

average = sum(responseTimesList)/len(responseTimesList)
print("The average of the list is %s" %average)
If you're having trouble with this, post your code.