How to create a loop based on time (a.k.a "Heartbeat")

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • v0id
    New Member
    • May 2010
    • 3

    #1

    How to create a loop based on time (a.k.a "Heartbeat")

    I'm wondering how can I create a time-based loop that runs based on a certain interval i.e. something similar to:

    while 1:
    # do something
    time.sleep(1)

    but more elegant and "balanced", in the above example if "do something" takes 500ms then the actual loop'll run every 1.5 instead of 1 second, and if this "do something" varies, the loop itself's unstable too.

    Any suggestions?
    Last edited by Niheel; May 10 '10, 11:31 AM. Reason: post relevant details only
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    You could use the built in time functions.

    Something like this:
    Code:
    while 1:
        now=time.time()
        print time.time()-now, "doing something"
        time.sleep(max[0,1-(time.time()-now)])

    Comment

    Working...