How to set a timer & clear a timer?

前端 未结 1 579
自闭症患者
自闭症患者 2021-02-06 01:55

I want to create a timer. When it times out, some actions will be taken. But, I can interrupt this timer and reset it. The pseudo code looks like below:

def timeo         


        
1条回答
  •  遥遥无期
    2021-02-06 02:20

    The threading.Timer() class is likely what you're looking for:

    from __future__ import print_function
    from time import sleep
    from random import random
    from threading import Timer
    
    def timeout():
        print("Alarm!")
    
    t = Timer(10.0, timeout)
    t.start()              # After 10 seconds, "Alarm!" will be printed
    
    sleep(5.0)
    if random() < 0.5:     # But half of the time
         t.cancel()        # We might just cancel the timer
         print('Canceling')
    

    0 讨论(0)
提交回复
热议问题