Equivalent of setInterval in python

前端 未结 4 1764
予麋鹿
予麋鹿 2020-12-13 10:21

I have recently posted a question about how to postpone execution of a function in Python (kind of equivalent to Javascript setTimeout) and it turns out to be a

4条回答
  •  悲&欢浪女
    2020-12-13 10:58

    Maybe a bit simpler is to use recursive calls to Timer:

    from threading import Timer
    import atexit
    
    class Repeat(object):
    
        count = 0
        @staticmethod
        def repeat(rep, delay, func):
            "repeat func rep times with a delay given in seconds"
    
            if Repeat.count < rep:
                # call func, you might want to add args here
                func()
                Repeat.count += 1
                # setup a timer which calls repeat recursively
                # again, if you need args for func, you have to add them here
                timer = Timer(delay, Repeat.repeat, (rep, delay, func))
                # register timer.cancel to stop the timer when you exit the interpreter
                atexit.register(timer.cancel)
                timer.start()
    
    def foo():
        print "bar"
    
    Repeat.repeat(3,2,foo)
    

    atexit allows to signal stopping with CTRL-C.

提交回复
热议问题