Python 时间延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3433559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:04:45  来源:igfitidea点击:

Python Time Delays

pythontime

提问by drnessie

I want to know how to call a function after a certain time. I have tried time.sleep() but this halts the whole script. I want the script to carry on, but after ???secs call a function and run the other script at the same time

我想知道如何在一段时间后调用函数。我试过 time.sleep() 但这会停止整个脚本。我希望脚本继续运行,但在 ???secs 调用一个函数并同时运行另一个脚本之后

采纳答案by Mark Byers

Have a look at threading.Timer. It runs your function in a new thread.

看看threading.Timer。它在新线程中运行您的函数。

from threading import Timer

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed

回答by jsbueno

If you want a function to be called after a while and not to stop your script you are inherently dealing with threaded code. If you want to set a function to be called and not to worry about it, you have to either explicitly use multi-threading - like em Mark Byers's answr, or use a coding framework that has a main loop which takes care of function dispatching for you - like twisted, qt, gtk, pyglet, and so many others. Any of these would require you to rewrite your code so that it works from that framework's main loop.

如果您希望在一段时间后调用一个函数而不是停止您的脚本,那么您本质上就是在处理线程代码。如果你想设置一个要调用的函数而不用担心它,你必须显式地使用多线程——比如 em Mark Byers 的 answr,或者使用一个具有主循环的编码框架来处理函数调度你 - 喜欢 Twisted、qt、gtk、pyglet 等等。其中任何一个都需要您重写代码,以便它从该框架的主循环中工作。

It is either that, or writing some main loop from event checking yourself on your code - All in all, if the only thing you want is single function calls, threading.Timer is the way to do it. If you want to use these timed calls to actually loop the program as is usually done with javascript's setTimeout, you are better of selecting one of the coding frameworks I listed above and refactoring your code to take advantage of it.

要么是这样,要么是通过对代码进行事件检查来编写一些主循环 - 总而言之,如果您唯一想要的是单个函数调用,那么 threading.Timer 就是这样做的方法。如果您想使用这些定时调用来实际循环程序,就像通​​常使用 javascript 的 setTimeout 完成的那样,您最好选择我上面列出的编码框架之一并重构您的代码以利用它。