我将如何在设定的毫秒数后执行一些代码?
我只想执行一次。
谢谢
有一个函数,它每毫秒在事件队列上pygame.time.set_timer(eventid, milliseconds)
生成一个带有 id的事件,然后你可以随意处理它。您可以通过调用来阻止事件再次生成。eventid
milliseconds
pygame.time.set_timer(eventid, 0)
SDL 有一个SDL_AddTimer
完全符合您要求的函数——您将一个回调函数传递给它,以便在延迟后执行,但是从文档中我真的找不到pygame
等效的。
对于 python 解决方案,您可以使用threading.Timer
该类。
看看模块sched — 事件调度器。链接中的示例非常简洁,可以帮助您入门
对于 python 解决方案 setTimeout 等效为:
import threading
def set_timeout(func, sec):
t = None
def func_wrapper():
func()
t.cancel()
t = threading.Timer(sec, func_wrapper)
t.start()
def hello():
print "Hello, world!"
set_timeout(hello, 0.1) # This is 0.1s = 100ms