Search code examples
pythonapscheduler

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()

Solution

  • 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()