How to Run a Mock Cron Pipeline Scheduler in Python
This code schedules a mock pipeline job to run every 2 seconds and hourly at :30 using the schedule library, then runs pending tasks for 10 seconds.
pip install schedule
Python code
20 linesimport time
import schedule
from datetime import datetime
def run_pipeline():
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Pipeline executed")
schedule.every(2).seconds.do(run_pipeline)
schedule.every().hour.at(":30").do(run_pipeline)
print("Scheduler started. Press Ctrl+C to stop.")
end_time = time.time() + 10
while time.time() < end_time:
schedule.run_pending()
time.sleep(1)
print("Scheduler stopped after 10 seconds.")
Output
Scheduler started. Press Ctrl+C to stop.
2025-04-23 10:15:00 - Pipeline executed
2025-04-23 10:15:02 - Pipeline executed
2025-04-23 10:15:04 - Pipeline executed
2025-04-23 10:15:06 - Pipeline executed
2025-04-23 10:15:08 - Pipeline executed
Scheduler stopped after 10 seconds.
How it works
The schedule library lets you define jobs with a human-readable syntax, like every(2).seconds or every().hour.at(":30"). In the loop, schedule.run_pending() checks which jobs are due and runs them. The time.sleep(1) keeps the loop from spinning too fast and wasting CPU. This pattern simulates a lightweight cron-like scheduler inside your Python process, useful for mock pipeline runs or simple automation before moving to production orchestration.
Common mistakes
- Forgetting to call `schedule.run_pending()` inside the loop, so jobs never run.
- Using `time.sleep(0)` which causes CPU spin and high usage.
- Not defining a stop condition, making the script run forever—add an end time or Ctrl+C handler.
Variations
- Use a while True loop with keyboard interrupt to run indefinitely until stopped.
- Replace the print with a real function that calls your pipeline or sends a message to a queue.
Real-world use cases
- Simulating a cron job on a local machine without setting up a real scheduler, for testing pipeline logic.
- Running a periodic health check or data refresh inside a long-lived Python service.
- Creating a lightweight mock job for integration tests that need time-based triggers.
Sponsored
More from Data pipelines & processing
- Add a UUID Surrogate Key to Each Row in a CSV with Python easy
- Attach Source File Metadata to Records in Python easy
- Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets medium
- Check Null Rate Threshold in PySpark DataFrame medium
- Count Records Processed per Category in Python easy
- Create Data Helper Functions in Python for Beginners easy
Keep learning
Related tutorials and quizzes for this topic.