0

I have a program that needs to execute every second. However I am concerned that the code would add a slight delay in turn causing it delay slightly longer then intended. Sample code:

while True:
    print(time)
    sleep(1)

In my case I will be adding more complicated function calls in this loop and am concerned that they will mess with my timer. Should I even be worried, and or is there another way for me to ensure this function loops every second?

Sumtinlazy
  • 337
  • 5
  • 17
  • 5
    You could use a library like [schedule](https://schedule.readthedocs.io/en/stable/). –  May 02 '18 at 09:19

1 Answers1

3

You can use this:

import threading

def scheduleFunc():
  threading.Timer(1.0, scheduleFunc).start()
  print(time)

Or use this:

import sched, time

scheduled = sched.scheduler(time.time, time.sleep)

def scheduleFunc(sc): 
    print(time)
    scheduled.enter(60, 1, scheduleFunc, (sc,))

scheduled.enter(60, 1, scheduleFunc, (scheduled,))
scheduled.run()
One Man Crew
  • 9,420
  • 2
  • 42
  • 51