Search code examples
pythonreal-time

How can I run a certain function for a specific time in Python?


For example i have function do_something() and I want it to run for exactly 1 second (and not .923 seconds. It won't do. However 0.999 is acceptable.)

However it is very very important that the do_something must exactly run for 1 second. I was thinking of using UNIX time stamp and calculate the seconds. But I am really wondering if Python has a way to do this in a more aesthetic way...

The function do_something() is long-running, and must be interrupted after exactly one second.


Solution

  • This bit of code might work for you. The description sounds like what you want:

    http://programming-guides.com/python/timeout-a-function

    It relies on the python signal module:

    http://docs.python.org/library/signal.html