222. Task Scheduling with APScheduler
πΉ 1. Installing APScheduler
Copy
pip install apschedulerβ Fix: Install APScheduler before using it.
πΉ 2. Basic APScheduler Job Example
Copy
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
Copy
β
Fix: date trigger runs once at a specific time.
πΉ 4. Scheduling a Recurring Job (Every Minute)
Copy
β
Fix: BackgroundScheduler() runs in non-blocking mode.
πΉ 5. Using Cron Jobs (Run at a Specific Time Daily)
Copy
β
Fix: cron trigger allows precise time-based scheduling.
πΉ 6. Passing Arguments to Scheduled Functions
Copy
β
Fix: Use args to pass arguments to scheduled functions.
πΉ 7. Listing All Scheduled Jobs
Copy
β
Fix: scheduler.get_jobs() retrieves all active jobs.
πΉ 8. Pausing and Resuming Jobs
Copy
β
Fix: pause_job() and resume_job() temporarily disable and enable jobs.
πΉ 9. Removing a Scheduled Job
Copy
β
Fix: remove_job('job_id') permanently deletes a job.
πΉ 10. Stopping the Scheduler Gracefully
Copy
β
Fix: scheduler.shutdown() stops all tasks safely.
π Summary: Why Use APScheduler?
FeatureAPScheduler
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?
ScenarioUse 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