Search code examples
pythonpython-2.7application-shutdownapscheduler

APscheduler will not stop


I have python code that I am developing for a website that, among other things, creates an excel sheet and then converts it into a json file. I need for this code to run continuously unless it is killed by the website administrator.

To this end, I am using APscheduler.

The code runs perfectly without APscheduler but when I attempt to add the rest of the code one of two things happens; 1) It runs forever and will not stop despite using "ctrl+C" and I need to stop it using task manager or 2) It only runs once, and then it stops

Code That doesn't Stop:

from apscheduler.scheduler import Scheduler
import logging
import time

logging.basicConfig()
sched = Scheduler()
sched.start()

(...)
code to make excel sheet and json file
(...)

@sched.interval_schedule(seconds = 15)
def job():
    excelapi_final()

while True:
    time.sleep(10)
sched.shutdown(wait=False)

Code that stops running after one time:

from apscheduler.scheduler import Scheduler
import logging
import time

logging.basicConfig()
sched = Scheduler()

(...)
#create excel sheet and json file
(...)

@sched.interval_schedule(seconds = 15)
def job():
    excelapi_final()
sched.start()

while True:
    time.sleep(10)
    sched.shutdown(wait=False)

I understand from other questions, a few tutorials and the documentation that sched.shutdown should allow for the code to be killed by ctrl+C - however that is not working. Any ideas? Thanks in advance!


Solution

  • You could use the standalone mode:

    sched = Scheduler(standalone=True)
    

    and then start the scheduler like this:

    try:
        sched.start()
    except (KeyboardInterrupt):
        logger.debug('Got SIGTERM! Terminating...')
    

    Your corrected code should look like this:

    from apscheduler.scheduler import Scheduler
    import logging
    import time
    
    logging.basicConfig()
    sched = Scheduler(standalone=True)
    
    (...)
    code to make excel sheet and json file
    (...)
    
    @sched.interval_schedule(seconds = 15)
    def job():
        excelapi_final()
    
    try:
        sched.start()
    except (KeyboardInterrupt):
        logger.debug('Got SIGTERM! Terminating...')
    

    This way the program will stop when Ctrl-C is pressed