What is the best way to repeatedly execute a function every x seconds?

后端 未结 18 2745
不知归路
不知归路 2020-11-21 06:04

I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C). This code will run as a daemon and is effectively like call

18条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:16

    Here is another solution without using any extra libaries.

    def delay_until(condition_fn, interval_in_sec, timeout_in_sec):
        """Delay using a boolean callable function.
    
        `condition_fn` is invoked every `interval_in_sec` until `timeout_in_sec`.
        It can break early if condition is met.
    
        Args:
            condition_fn     - a callable boolean function
            interval_in_sec  - wait time between calling `condition_fn`
            timeout_in_sec   - maximum time to run
    
        Returns: None
        """
        start = last_call = time.time()
        while time.time() - start < timeout_in_sec:
            if (time.time() - last_call) > interval_in_sec:
                if condition_fn() is True:
                    break
                last_call = time.time()
    

提交回复
热议问题