简体   繁体   English

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

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

Is there a way to, for example, print Hello World! 有没有办法打印例如Hello World! every n seconds after x seconds? x秒后每隔n秒? Looking at this: Run certain code every n seconds , I know how to run a code every n seconds. 看一下: 每n秒运行某些代码 ,我知道如何每n秒运行代码。 But I would like to run certain code after x seconds every n seconds. 但是我想每n秒在x秒之后运行某些代码。

Need some guidance on how to do this. 需要有关如何执行此操作的一些指导。

Key condition: The program should not lag or sleep. 关键条件:程序不应滞后或休眠。 The certain code I am referring to is a function call. 我所指的某些代码是一个函数调用。

Can you just do something like (to run it after 5 seconds, and it'll run every 10 seconds): 您能做点什么(在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)

A: Yes, both ways are possible 答:是的,两种方法都可行

For a given task, give a try to use Tkinter internal scheduling, which does not block. 对于给定的任务,请尝试使用不阻塞的 Tkinter内部调度

Key methods are: 关键方法是:

 .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>

more smart options available 提供更多智能选项

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