What is the best way to repeatedly execute a function every x seconds?

后端 未结 18 2691
不知归路
不知归路 2020-11-21 06:04

I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C). This code will run as a daemon and is effectively like call

18条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 06:20

    I use Tkinter after() method, which doesn't "steal the game" (like the sched module that was presented earlier), i.e. it allows other things to run in parallel:

    import Tkinter
    
    def do_something1():
      global n1
      n1 += 1
      if n1 == 6: # (Optional condition)
        print "* do_something1() is done *"; return
      # Do your stuff here
      # ...
      print "do_something1() "+str(n1)
      tk.after(1000, do_something1)
    
    def do_something2(): 
      global n2
      n2 += 1
      if n2 == 6: # (Optional condition)
        print "* do_something2() is done *"; return
      # Do your stuff here
      # ...
      print "do_something2() "+str(n2)
      tk.after(500, do_something2)
    
    tk = Tkinter.Tk(); 
    n1 = 0; n2 = 0
    do_something1()
    do_something2()
    tk.mainloop()
    

    do_something1() and do_something2() can run in parallel and in whatever interval speed. Here, the 2nd one will be executed twice as fast.Note also that I have used a simple counter as a condition to terminate either function. You can use whatever other contition you like or none if you what a function to run until the program terminates (e.g. a clock).

提交回复
热议问题