繁体   English   中英

在python中每n秒在x秒后运行某些代码

[英]Run certain code after x seconds, every n seconds in python

有没有办法打印例如Hello World! x秒后每隔n秒? 看一下: 每n秒运行某些代码 ,我知道如何每n秒运行代码。 但是我想每n秒在x秒之后运行某些代码。

需要有关如何执行此操作的一些指导。

关键条件:程序不应滞后或休眠。 我所指的某些代码是一个函数调用。

您能做点什么(在5秒钟后运行,然后每10秒钟运行一次)吗:

import time

time.sleep(5)

while True:
    your code
    time.sleep(10)
import threading
import time

def printit():
  threading.Timer(n, printit).start()
  print "Hello, World!"

threading.Timer(x, printit)

答:是的,两种方法都可行

对于给定的任务,请尝试使用不阻塞的 Tkinter内部调度

关键方法是:

 .after( n_msec_from_now, aScheduledFuncCALL )  # to plan a call not before n_msec-s
 .after_idle(             aScheduledFuncCALL )  # to plan a call after GUI gets <idle>

提供更多智能选项

import Tkinter as tk

def RunCertainCodeCALL():
    #a CertainCode
    root.after( x * 1000, RunCertainCodeCALL )  # .SET for next round of schedulling

root = tk.Tk()
root.after( x * 1000, RunCertainCodeCALL )      # .SET for 1-st round of schedulling
root.mainloop()                                 # .GUI mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM