Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Event scheduler in Python
Python provides the schedule module for running tasks at specific times. This module offers a simple and intuitive way to create scheduled jobs using the every() function with various time intervals.
Installation
First, install the schedule module ?
pip install schedule
Syntax
schedule.every(n).[timeframe]
Where:
- n is the time interval (integer)
- timeframe can be seconds, minutes, hours, days, or weekday names (monday, tuesday, etc.)
Basic Example
Here's a simple example that prints messages at different intervals ?
import schedule
import time
def job():
print("Job is running...")
def daily_task():
print("Daily task executed!")
# Schedule jobs
schedule.every(2).seconds.do(job)
schedule.every().minute.do(lambda: print("One minute passed"))
schedule.every().hour.do(lambda: print("One hour passed"))
# Run for 10 seconds to see output
start_time = time.time()
while time.time() - start_time < 10:
schedule.run_pending()
time.sleep(1)
print("Demo completed")
Job is running... One minute passed Job is running... Job is running... Job is running... Job is running... Demo completed
Advanced Scheduling Options
The schedule module supports various scheduling patterns ?
import schedule
def task():
print("Task executed")
# Different scheduling options
schedule.every(10).seconds.do(task) # Every 10 seconds
schedule.every().minute.do(task) # Every minute
schedule.every().hour.do(task) # Every hour
schedule.every().day.at("10:30").do(task) # Daily at 10:30 AM
schedule.every().monday.do(task) # Every Monday
schedule.every().wednesday.at("13:15").do(task) # Wednesday at 1:15 PM
print("Scheduled jobs:")
for job in schedule.jobs:
print(f"- {job}")
Scheduled jobs: - Every 10 seconds do task() (last run: [never], next run: 2024-01-01 12:00:10) - Every 1 minute do task() (last run: [never], next run: 2024-01-01 12:01:00) - Every 1 hour do task() (last run: [never], next run: 2024-01-01 13:00:00) - Every day at 10:30:00 do task() (last run: [never], next run: 2024-01-02 10:30:00) - Every Monday at 00:00:00 do task() (last run: [never], next run: 2024-01-08 00:00:00) - Every Wednesday at 13:15:00 do task() (last run: [never], next run: 2024-01-03 13:15:00)
Practical Example with Functions
Here's a practical example that demonstrates scheduling different tasks ?
import schedule
import time
from datetime import datetime
def backup_files():
print(f"[{datetime.now().strftime('%H:%M:%S')}] Backing up files...")
def send_report():
print(f"[{datetime.now().strftime('%H:%M:%S')}] Sending daily report...")
def cleanup_logs():
print(f"[{datetime.now().strftime('%H:%M:%S')}] Cleaning up old logs...")
def system_check(system_name):
print(f"[{datetime.now().strftime('%H:%M:%S')}] Checking {system_name} system...")
# Schedule different tasks
schedule.every(3).seconds.do(backup_files)
schedule.every(5).seconds.do(send_report)
schedule.every(7).seconds.do(cleanup_logs)
schedule.every(4).seconds.do(system_check, "database")
# Run scheduler for demonstration
print("Starting scheduler...")
start_time = time.time()
while time.time() - start_time < 15:
schedule.run_pending()
time.sleep(1)
print("Scheduler stopped")
Starting scheduler... [12:00:03] Backing up files... [12:00:04] Checking database system... [12:00:05] Sending daily report... [12:00:06] Backing up files... [12:00:07] Cleaning up old logs... [12:00:08] Checking database system... [12:00:09] Backing up files... [12:00:10] Sending daily report... [12:00:12] Backing up files... [12:00:12] Checking database system... [12:00:14] Cleaning up old logs... [12:00:15] Backing up files... Scheduler stopped
Canceling Jobs
You can cancel scheduled jobs when needed ?
import schedule
def temporary_job():
print("This job will be canceled")
return schedule.CancelJob # Cancel this job after first run
def permanent_job():
print("This job continues running")
# Schedule jobs
job1 = schedule.every(2).seconds.do(temporary_job)
job2 = schedule.every(3).seconds.do(permanent_job)
print(f"Initially scheduled jobs: {len(schedule.jobs)}")
# Cancel a specific job
schedule.cancel_job(job1)
print(f"After canceling job1: {len(schedule.jobs)}")
# Clear all jobs
schedule.clear()
print(f"After clearing all jobs: {len(schedule.jobs)}")
Initially scheduled jobs: 2 After canceling job1: 1 After clearing all jobs: 0
Key Features
| Feature | Example | Description |
|---|---|---|
| Time intervals | every(5).seconds |
Run every 5 seconds |
| Specific times | every().day.at("09:00") |
Run daily at 9:00 AM |
| Weekdays | every().monday |
Run every Monday |
| Parameters | do(func, arg1, arg2) |
Pass arguments to functions |
Conclusion
The schedule module provides an elegant way to handle task scheduling in Python. Use schedule.every() with time intervals for periodic tasks and .at() for specific times. Remember to call schedule.run_pending() in a loop to execute scheduled jobs.
