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