222. Task Scheduling with APScheduler


πŸ”Ή 1. Installing APScheduler

pip install apscheduler

βœ… Fix: Install APScheduler before using it.


πŸ”Ή 2. Basic APScheduler Job Example

from apscheduler.schedulers.blocking import BlockingScheduler

def job():
    print("Hello, APScheduler!")

scheduler = BlockingScheduler()
scheduler.add_job(job, 'interval', seconds=5)  # Runs every 5 seconds
scheduler.start()

βœ… Fix: BlockingScheduler() runs indefinitely until manually stopped.


πŸ”Ή 3. Scheduling a Job at a Specific Time

from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime, timedelta

def scheduled_task():
    print("Scheduled task executed!")

scheduler = BlockingScheduler()
run_time = datetime.now() + timedelta(seconds=10)  # Runs 10 seconds from now
scheduler.add_job(scheduled_task, 'date', run_date=run_time)
scheduler.start()

βœ… Fix: date trigger runs once at a specific time.


πŸ”Ή 4. Scheduling a Recurring Job (Every Minute)

βœ… Fix: BackgroundScheduler() runs in non-blocking mode.


πŸ”Ή 5. Using Cron Jobs (Run at a Specific Time Daily)

βœ… Fix: cron trigger allows precise time-based scheduling.


πŸ”Ή 6. Passing Arguments to Scheduled Functions

βœ… Fix: Use args to pass arguments to scheduled functions.


πŸ”Ή 7. Listing All Scheduled Jobs

βœ… Fix: scheduler.get_jobs() retrieves all active jobs.


πŸ”Ή 8. Pausing and Resuming Jobs

βœ… Fix: pause_job() and resume_job() temporarily disable and enable jobs.


πŸ”Ή 9. Removing a Scheduled Job

βœ… Fix: remove_job('job_id') permanently deletes a job.


πŸ”Ή 10. Stopping the Scheduler Gracefully

βœ… Fix: scheduler.shutdown() stops all tasks safely.


πŸš€ Summary: Why Use APScheduler?

Feature
APScheduler

One-time execution

βœ… date trigger for scheduled one-time jobs

Recurring execution

βœ… interval trigger for repeated jobs

Cron-like scheduling

βœ… cron trigger for daily/hourly jobs

Background scheduling

βœ… BackgroundScheduler() for non-blocking execution

Job control

βœ… Pause, resume, or remove jobs dynamically


πŸš€ When to Use APScheduler?

Scenario
Use APScheduler?

Running periodic background tasks

βœ… Yes

Replacing cron jobs with Python

βœ… Yes

Automating data collection or cleanup

βœ… Yes

Triggering scheduled API calls

βœ… Yes

Replacing Celery for lightweight scheduling

βœ… Yes (but not for distributed tasks)


Last updated