Scheduling tasks to run at specific intervals or during certain conditions is a common requirement for many applications. wo popular approaches are using Windows built-in Task Scheduler versus leveraging APScheduler, a Python-based scheduling library. Let’s compare these two approaches by taking a look at two examples:
- Using APScheduler to define more sophisticated scheduling logic with Cron-like triggers.
- Running a scheduled task using Windows Task Scheduler with a simple batch file.
Approach 1: Using Windows Built-in Task Scheduler with a Batch File
Windows Task Scheduler is a native tool in the Windows operating system that allows users to schedule any program or script to run automatically at specific times or intervals.
A common way to automate Python scripts is by creating a .bat (batch) file that runs the script when triggered by the scheduler. Here’s a typical example of such a batch file:
batchCopyEdit@echo off
cd /d "%~dp0"
python script.py
pause
Approach 2: Using APScheduler with BackgroundScheduler
APScheduler (Advanced Python Scheduler) is a Python library designed to run jobs at specified times or intervals. Unlike Windows Task Scheduler, APScheduler gives you more power to control how and when jobs are executed. It supports several types of triggers, such as interval, cron, date, and more.
Let’s take a look at an example where we use APScheduler to run a task based on a cron trigger for the third Friday of June and December:
from apscheduler.triggers.cron import CronTrigger
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
import logging
scheduler = BackgroundScheduler()
def is_third_friday(year, month, day):
"""Check if the given date is the third Friday of the month"""
if datetime(year, month, day).weekday() != 4: # Friday is weekday 4
return False
# Check if it's the third Friday
return (day - 1) // 7 == 2 # Third week
@scheduler.add_job(
CronTrigger(
month='6,12', # June and December
day='15-21', # Third week range (15th-21st)
hour=9, # 9 AM
minute=0
),
id='semi_annual_task'
)
def semi_annual_recon():
"""Runs every third Friday of June and December at 9 AM"""
now = datetime.now()
if is_third_friday(now.year, now.month, now.day):
logger.info("Running semi-annual recon task")
try:
# Your recon logic here
logger.info("Semi-annual recon completed successfully")
except Exception as e:
logger.error(f"Error in semi-annual recon: {str(e)}")
scheduler.start()
It facilitates dynamic job management and offers flexibility in triggering options, including intervals such as every n seconds, specific dates like every third Friday in June, or cron expressions. By utilizing the @scheduler.add_job decorator, users can easily schedule jobs, making it more powerful and flexible than the Windows Task Scheduler. This allows for programmatic control and the ability to establish multiple schedulers.