0

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?

GG.
  • 21,083
  • 14
  • 84
  • 130
  • 6
    Yes, use an external scheduler to run your Job. If you use linux you have cron at your belt. Windows have a task scheduler too. – Caio Belfort Jan 10 '21 at 01:39
  • Have you tried running the script? What happened? What "resources" do you imagine its using? Have you tried researching alternatives? – Mad Physicist Jan 10 '21 at 01:39
  • 1
    You'll only be wasting resources if you take some sort of a lock on a shared resource (e.g. on a file or in a database) before going into that `sleep`. – Samwise Jan 10 '21 at 01:39
  • Does this answer your question? [What is the best way to repeatedly execute a function every x seconds?](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds) – Gino Mempin Jan 10 '21 at 02:45

2 Answers2

3

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).

Dave
  • 7,555
  • 8
  • 46
  • 88
Leemosh
  • 883
  • 6
  • 19
  • 1
    Why? As in, what problems does `appscheduler` solve that just `sleep`ing for a long produces? – Dave Jan 13 '22 at 00:50
  • Imagine you wanna run something every 12 hours but the processing is taking 11 hours. What would sleep do is that you'd start the app, it would run 11 hours and then you'd wait another 12 hours with sleep. The interval would be 23 hours instead of 12. – Leemosh Jan 13 '22 at 12:16
1

this timing is not accurate as it only count time when cpu is sheduled on this process at least you can check target time is arrived every several second and this is not a good solution as your process is less reliable than system cron. your process may hang due to unknown bugs and on system high cpu/mem utilization

cdarlint
  • 1,485
  • 16
  • 14