简体   繁体   中英

Run certain code after x seconds, every n seconds in python

Is there a way to, for example, print Hello World! every n seconds after x seconds? Looking at this: Run certain code every n seconds , I know how to run a code every n seconds. But I would like to run certain code after x seconds every n seconds.

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):

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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