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

后端 未结 18 3054
不知归路
不知归路 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

    If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.

    import sched, time
    s = sched.scheduler(time.time, time.sleep)
    def do_something(sc): 
        print("Doing stuff...")
        # do your stuff
        s.enter(60, 1, do_something, (sc,))
    
    s.enter(60, 1, do_something, (s,))
    s.run()
    

    If you're already using an event loop library like asyncio, trio, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.

提交回复
热议问题