Python时间延迟

Posted

技术标签:

【中文标题】Python时间延迟【英文标题】:Python time delay 【发布时间】:2015-01-12 03:36:53 【问题描述】:

好的,我想知道如何在不暂停整个程序的情况下延迟程序的一部分。 我不一定擅长python,所以如果可能的话,如果你能给我一个相对简单的答案,那就太好了。

每次调用此函数时,我都想让乌龟在屏幕上画一个圆圈,这就是我所拥有的:

import time
from random import randint
turtle5 = turtle.Turtle()    

coinx = randint(-200, 200)
coiny = randint(-200, 200)

turtle5.pu()
turtle5.goto(coinx, coiny)
turtle5.pd()
turtle5.begin_fill()
turtle5.fillcolor("Gold")
turtle5.circle(5, 360, 8)
turtle5.end_fill()
time.sleep(1)
turtle5.clear()

【问题讨论】:

哪个函数?您发布的代码中没有任何功能。 Alright,你必须更具体。 您说您想要“延迟程序的一部分而不暂停整个程序”。好的,那么当你的程序绘制海龟时,你的程序会在延迟时间内做什么? 【参考方案1】:

turtle.ontimer()以指定的延迟调用函数:

turtle.ontimer(your_function, delay_in_milliseconds)

【讨论】:

【参考方案2】:

你需要把你想要延迟的部分程序放在它自己的线程中,然后在那个线程中调用sleep()。

我不确定你在你的例子中到底想做什么,所以这里是一个简单的例子:

import time
import threading

def print_time(msg):
    print 'The time %s is: %s.' % (msg, time.ctime(time.time()))

class Wait(threading.Thread):
    def __init__(self, seconds):
        super(Wait, self).__init__()
        self.seconds = seconds
    def run(self):
        time.sleep(self.seconds)
        print_time('after waiting %d seconds' % self.seconds)

if __name__ == '__main__':
    wait_thread = Wait(5)
    wait_thread.start()
    print_time('now')

输出:

The time now is: Mon Jan 12 01:57:59 2015.
The time after waiting 5 seconds is: Mon Jan 12 01:58:04 2015.

请注意,我们启动了将首先等待 5 秒的线程,但它并没有阻塞 print_time('now') 调用,而是在后台等待。

编辑:

根据 J.F. Sebastian 的评论,使用线程的更简单的解决方案是:

import time
import threading

def print_time(msg):
    print 'The time %s is: %s.' % (msg, time.ctime(time.time()))

if __name__ == '__main__':
    t = threading.Timer(5, print_time, args = ['after 5 seconds'])
    t.start()
    print_time('now')

【讨论】:

这里不需要自定义线程子类。有threading.Timer。您可以避免在 GUI(如turtle)、网络代码中创建线程。见Postponing functions in python

以上是关于Python时间延迟的主要内容,如果未能解决你的问题,请参考以下文章

python如何按规定的时间延迟?

Apache Beam Python SDK 会丢弃延迟数据,还是无法配置延迟参数?

Python 时间延迟

如何在Python中进行时间延迟[重复]

在 Python 中组合多个音频文件(有延迟)

Python:无重复延迟的键盘输入