【问题标题】:How set a loop that repeats at a certain interval in python? [duplicate]如何在python中设置一个以一定间隔重复的循环? [复制]
【发布时间】:2015-11-02 08:58:23
【问题描述】:

我是 python 新手,我想知道是否有一个函数可以在特定时间间隔重复一个事件,有点像

setInterval()

在 Javascript 中。我知道我可以使用

time.sleep()

在常规循环中,但我想知道是否有更好的方法来做到这一点。提前致谢。

【问题讨论】:

  • 您将需要线程。请参阅this question(或其他人在 Google 上搜索)。

标签: python loops time timer


【解决方案1】:

以下是@Mathias Ettinger 的简化版

因为call_at_interval 已经在一个单独的线程中运行,所以没有必要使用Timer,因为它会产生另一个线程。

只是休眠,直接调用回调。

from threading import Thread
from time import sleep

def call_at_interval(period, callback, args):
    while True:
        sleep(period)
        callback(*args)

def setInterval(period, callback, *args):
    Thread(target=call_at_interval, args=(period, callback, args)).start()

def hello(word):
    print("hello", word)

setInterval(10, hello, 'world!')

【讨论】:

    【解决方案2】:
    from threading import Timer, Thread
    
    def call_at_interval(time, callback, args):
        while True:
            timer = Timer(time, callback, args=args)
            timer.start()
            timer.join()
    
    def setInterval(time, callback, *args):
        Thread(target=call_at_interval, args=(time, callback, args)).start()
    

    需要这两个函数来避免使setInterval 成为阻塞调用。

    你可以这样使用它:

    def hello(word):
        print("hello", word)
    
    setInterval(10, hello, 'world!')
    

    它将每十秒打印一次'hello world!'

    【讨论】:

      猜你喜欢
      • 2018-03-25
      • 2016-10-02
      • 1970-01-01
      • 2015-02-20
      • 1970-01-01
      • 2012-11-27
      • 2013-09-10
      • 2014-01-07
      • 2018-09-02
      相关资源
      最近更新 更多