Milano
Milano

Reputation: 18745

Repeat if method is being executed certain time

Is there a way to interrupt executing a method and repeat it in case the time is out?

For example method connection which connects to some server.

try:
    connection(server,5)
except:
    repeat

Let's have a situation when method connection is running more than 5 seconds. Then I want to raise exception and repeat it. The exception is not necessary I want just repeat it.

I'm thinking about make a second thread which checks time and when the time is out interruption of the method in another thread is provided but there should be a more simple solution in my opinion.

Upvotes: 1

Views: 60

Answers (1)

Fame Castle
Fame Castle

Reputation: 33

You could use threading.

Code:

import threading
success = False
def connect():
    global success
    connection(server,5)
    success = True
th = threading.Thread(target=connect)
th.start()
time.sleep(5) #timeout 5 sec
if success:
    yuhuuu   
else:
    th.stop() #kill task

Upvotes: 1

Related Questions