Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using APSchedule and time.sleep() in Python

I am creating a script that has a function that should run every X hour.

One way of doing it seems to be with time.sleep(). Example taken from this Stackoverflow question.

import time 
while True:
    print "This prints once a minute."
    time.sleep(60)  # Delay for 1 minute (60 seconds)

The other way seems to be with APScheduler. Example taken from this documentation.

from apscheduler.scheduler import Scheduler

sched = Scheduler()

@sched.interval_schedule(hours=3)
def some_job():
    print "Decorated job"

sched.configure(options_from_ini_file)
sched.start()

What is the best way of doing this? What are the pros and cons of the different ways? The script will be a daemon later on if that changes anything.

like image 455
Filip Avatar asked Dec 04 '25 05:12

Filip


1 Answers

Whether or not APScheduler brings you any benefit depends on your requirements. People who use APScheduler usually have more specific requirements or need to add/remove jobs dynamically.

For example, if your daemon is shut down and the task misses its deadline, how do you want to handle that? If you need any such advanced task management capabilities, then you will want to use APScheduler. Otherwise, you can stick with time.sleep().

like image 74
Alex Grönholm Avatar answered Dec 05 '25 19:12

Alex Grönholm