Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Apscheduler not stopping a job even after using 'remove_job'

This is my code

I'm using the remove_job and the shutdown functions of the scheduler to stop a job, but it keeps on executing.

What is the correct way to stop a job from executing any further?

from apscheduler.schedulers.background import BlockingScheduler

def job_function():
    print "job executing"


scheduler = BlockingScheduler(standalone=True)
scheduler.add_job(job_function, 'interval', seconds=1, id='my_job_id')


scheduler.start()
scheduler.remove_job('my_job_id')
scheduler.shutdown()
like image 229
wolfgang Avatar asked Oct 09 '15 10:10

wolfgang


2 Answers

Simply ask the scheduler to remove the job inside the job_function using the remove_function as @Akshay Pratap Singh Pointed out correctly, that the control never returns back to start()

from apscheduler.schedulers.background import BlockingScheduler

count = 0

def job_function():
    print "job executing"
    global count, scheduler

    # Execute the job till the count of 5 
    count = count + 1
    if count == 5:
        scheduler.remove_job('my_job_id')


scheduler = BlockingScheduler()
scheduler.add_job(job_function, 'interval', seconds=1, id='my_job_id')


scheduler.start()
like image 57
wolfgang Avatar answered Oct 18 '22 16:10

wolfgang


As you are using BlockingScheduler , so first you know it's nature.

So, basically BlockingScheduler is a scheduler which runs in foreground(i.e start() will block the program).In laymen terms, It runs in the foreground, so when you call start(), the call never returns. That's why all lines which are followed by start() are never called, due to which your scheduler never stopped.

BlockingScheduler can be useful if you want to use APScheduler as a standalone scheduler (e.g. to build a daemon).


Solution

If you want to stop your scheduler after running some code, then you should opt for other types of scheduler listed in ApScheduler docs.

I recommend BackgroundScheduler, if you want the scheduler to run in the background inside your application/program which you can pause, resume and remove at anytime, when you need it.

like image 29
Akshay Pratap Singh Avatar answered Oct 18 '22 15:10

Akshay Pratap Singh