3

I have a while loop which contains a process which takes roughly 1 second each time but occasionally takes over 5 minutes. I want the loop to terminate after 2 seconds in case this 5 minute scenario occurs. I have already tried

import time
t1 = time.time() + 2
while time.time() < t1:
    PerformProcess

but this approach is limited by the fact that PerformProcess is automatically terminated each time time.time() is calculated.

The other solution i have commonly seen posted is

import time
t1 = time.time()
t2 = time.time()
while t2 - t1 < 2:
    PerformProcess
    t2 = time.time()

but this approach does not work as the refresh for t2 will not be reached if it does the 5 minute process.

I essentially just need a way to terminate the while loop after 2 seconds such that there is no time calculation done inside the while loop and/or such that the time calculation does not terminate the process within the while loop.

In case it's helpful, the PerformProcess is essentially opening a web page using urllib and extracting data from it. The simplified version of what it does is essentially

import urllib
f = urllib.urlopen(str(Hyperlink))
s = f.read()
print s
f.close()

where f is what usually takes 1 second but sometimes, for some reason, takes far longer.

Statisdisc
  • 33
  • 3
  • lunch your process as subprocess/thread/something and then run a lopp that counts time and kill that something. – Tymoteusz Paul Dec 30 '13 at 16:48
  • Calling `time.time()` does not terminate `PerformProcess`; rather, `time.time()` is not called *until* `PerformProcess` finishes on its own. – chepner Dec 30 '13 at 16:49
  • What platform are you on? I have a simple solution for you, which uses SIGALRM, but it will not work on Windows. If you're on windows I have a more complex solution involving threading. – wim Dec 30 '13 at 17:07
  • Yeah, Windows I'm afraid. Never used threading before but would love to see your solution! – Statisdisc Dec 30 '13 at 17:12
  • See if this helps: http://stackoverflow.com/questions/6068361/kill-a-function-after-a-certain-time-in-windows – hkk Dec 30 '13 at 17:14
  • 1
    Aha. Use `urllib2` instead of `urllib`, then you will have timeout kwarg. – wim Dec 30 '13 at 17:19
  • By the way, if you don't mind to go outside core libraries then python [requests](https://pypi.python.org/pypi/requests) module is so much nicer to work with. – wim Dec 30 '13 at 17:21

1 Answers1

3

If I understand correctly, the timeout you are trying to set is in relation to the url fetch. I'm not sure what version of python you are using but if you are using 2.6+ then I am wondering if something like this might be what your looking to do:

import urllib2
f = urllib2.urlopen(str(Hyperlink), timeout=2)

You would then need to wrap in a try/except and do something if the timeout occurs.

clutton
  • 620
  • 1
  • 8
  • 18