简体   繁体   中英

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.

I gather from comments that there's a while loop in here somewhere. Here's a class that subclasses Thread , based on the source code for _Timer in the threading module. I know you said you decided against threading, but this is just a timer control thread; do_something executes in the main thread. So this should be clean. (Someone correct me if I'm wrong!):

from threading import Thread, Event

class BoolTimer(Thread):
    """A boolean value that toggles after a specified number of seconds:

    bt = BoolTimer(30.0, False)
    bt.start()
    bt.cancel() # prevent the booltimer from toggling if it is still waiting
    """

    def __init__(self, interval, initial_state=True):
        Thread.__init__(self)
        self.interval = interval
        self.state = initial_state
        self.finished = Event()

    def __nonzero__(self):
        return bool(self.state)

    def cancel(self):
        """Stop BoolTimer if it hasn't toggled yet"""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.state = not self.state
        self.finished.set()

You could use it like this.

import time

def do_something():
    running = BoolTimer(1.0)
    running.start()
    while running:
        print "running"              # Do something more useful here.
        time.sleep(0.05)             # Do it more or less often.
        if not running:              # If you want to interrupt the loop, 
            print "broke!"           # add breakpoints.
            break                    # You could even put this in a
        time.sleep(0.05)             # try, finally block.

do_something()

The 'sched' module of Python appears suitable:

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

Apart from that: Python is not a real-time language nor does it usually run on a real-time OS. So your requirement is kind of questionable.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM