Search code examples
pythoncrondaemonapscheduler

Best way to keep Python script running?


I'm using APScheduler to run some recurring tasks as follows:

from apscheduler.scheduler import Scheduler
from time import time, sleep

apsched = Scheduler()
apsched.start()

def doSomethingRecurring():
    pass  # Do something really interesting here..

apsched.add_interval_job(doSomethingRecurring, seconds=2)

while True:
    sleep(10)

Because the interval_job ends when this script ends I simply added the ending while True loop. I don't really know if this is the best, let alone pythonic way to do this though. Is there a "better" way of doing this? All tips are welcome!


Solution

  • Try using the blocking scheduler. apsched.start() will just block. You have to set it up before starting.

    EDIT: Some pseudocode in response to the comment.

    apsched = BlockingScheduler()
    
    def doSomethingRecurring():
        pass  # Do something really interesting here..
    
    apsched.add_job(doSomethingRecurring, trigger='interval', seconds=2)
    
    apsched.start() # will block