Python Time Delays

前端 未结 2 992
走了就别回头了
走了就别回头了 2020-11-27 06:07

I want to know how to call a function after a certain time. I have tried time.sleep() but this halts the whole script. I want the script to carry on, but after ???secs cal

相关标签:
2条回答
  • 2020-11-27 06:19

    If you want a function to be called after a while and not to stop your script you are inherently dealing with threaded code. If you want to set a function to be called and not to worry about it, you have to either explicitly use multi-threading - like em Mark Byers's answr, or use a coding framework that has a main loop which takes care of function dispatching for you - like twisted, qt, gtk, pyglet, and so many others. Any of these would require you to rewrite your code so that it works from that framework's main loop.

    It is either that, or writing some main loop from event checking yourself on your code - All in all, if the only thing you want is single function calls, threading.Timer is the way to do it. If you want to use these timed calls to actually loop the program as is usually done with javascript's setTimeout, you are better of selecting one of the coding frameworks I listed above and refactoring your code to take advantage of it.

    0 讨论(0)
  • 2020-11-27 06:21

    Have a look at threading.Timer. It runs your function in a new thread.

    from threading import Timer
    
    def hello():
        print "hello, world"
    
    t = Timer(30.0, hello)
    t.start() # after 30 seconds, "hello, world" will be printed
    
    0 讨论(0)
提交回复
热议问题