By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,842 Members | 2,154 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,842 IT Pros & Developers. It's quick & easy.

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

P: 3
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

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?
May 5 '10 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 391
You could use the built in time functions.

Something like this:
Expand|Select|Wrap|Line Numbers
  1. while 1:
  2.     now=time.time()
  3.     print time.time()-now, "doing something"
  4.     time.sleep(max[0,1-(time.time()-now)])
May 10 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.