Search code examples
pythonsleep

Issues with sleeping for several hours?


I want to run a script, or at least the block of code in it every 12 hours. How bad/ how much resources will I be wasting by using:

while True:
    My Code
    time.sleep(43200)

Is there an easier and more efficient way to accomplish this?


Solution

  • I'd recommend using apscheduler if you need to run the code once in an hour (or more):

    from apscheduler.schedulers.blocking import BlockingScheduler
    
    def main():
       Do something
    
    scheduler = BlockingScheduler()
    scheduler.add_job(main, "interval", hours=12)
    scheduler.start()
    

    apscheduler provides more controlled and consistent timing of when the operation will be executed. For example, if you want to run something every 12 hours but the processing takes 11 hours, then a sleep based approach would end up executing every 23 hours (11 hours running + 12 hours sleeping).