Since the user didn't specify an environment, I'll start with a typical example of a script using "if __name__ == '__main__':" and mention that the necessary packages should be installed via pip.
I’ll show a concise program using APScheduler, which includes job scheduling with both interval and cron triggers. I will also summarize key components in a short explanation to ensure clarity without getting too lengthy. Let's create a clear and informative response for the user! Below is a complete, minimal example of using APScheduler to schedule and run periodic tasks in Python.
1. Install APScheduler
bash
pip install apscheduler
2. Example program: scheduler_example.py
python
from datetime import datetime
import time
import logging
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.triggers.cron import CronTrigger
# Configure basic logging so you can see what's happening
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
def simple_task():
"""A simple task that just prints the current time."""
logger.info(f"Running simple_task at {datetime.now()}")
def periodic_task(name):
"""A task that takes an argument."""
logger.info(f"Running periodic_task({name}) at {datetime.now()}")
def main():
scheduler = BackgroundScheduler()
# 1) Run simple_task every 10 seconds
scheduler.add_job(
simple_task,
trigger=IntervalTrigger(seconds=10),
id="simple_task_job",
max_instances=1, # avoid overlapping runs
replace_existing=True, # replace job if already exists
)
# 2) Run periodic_task every minute at second 5
scheduler.add_job(
periodic_task,
trigger=CronTrigger(second=5), # second=5 of every minute
args=["APScheduler"],
id="periodic_task_job",
max_instances=1,
replace_existing=True,
)
# Start the scheduler
scheduler.start()
logger.info("Scheduler started. Press Ctrl+C to exit.")
try:
# Keep the main thread alive to let BackgroundScheduler run jobs
while True:
time.sleep(1)
except (KeyboardInterrupt, SystemExit):
logger.info("Shutting down scheduler...")
scheduler.shutdown()
logger.info("Scheduler shut down.")
if __name__ == "__main__":
main()
3. Run it
bash
python scheduler_example.py
You’ll see log messages every 10 seconds from simple_task and once per minute (at second 5) from periodic_task.
If you’d like, I can extend this example to include:
Running one-time (date) jobs
Using BlockingScheduler instead of BackgroundScheduler
Storing jobs in a database (e.g., SQLite) so they persist across restarts.