usleep in Python

后端 未结 8 991
执笔经年
执笔经年 2020-12-09 02:58

I was searching for a usleep() function in Python 2.7.

Does anybody know if it does exist, maybe with another function name?

8条回答
  •  一个人的身影
    2020-12-09 03:18

    Be very very careful with time.sleep. I got burned by python3 using time.sleep because it is non-monotonic. If the wall clock changes backwards, the time.sleep call won't finish until the wall clock catches up with where it would have been if the sleep had gone forward as planned. I have not yet found a monotonic blocked sleep for python.

    Instead, I recommend Event.wait, like this:

    def call_repeatedly(interval, func, *args, **kwargs):
        stopped = Event()
        def loop():
            while not stopped.wait(interval):  # the first call is in `interval` secs
                try:
                    func(*args)
                except Exception as e:
                    logger.error(e);
                    if kwargs.get('exception'):
                        kwargs.get('exception')(e) # SEND exception to the specified function if there is one.
                    else:
                        raise Exception(e)
        Thread(target=loop).start()
        return stopped.set
    

    http://pastebin.com/0rZdY8gB

提交回复
热议问题