Logo
All Questions

Design a task scheduler in Python.

DifficultyalgorithmsAsked at Google

Question Explain

Designing a task scheduler in Python means to write a code that can schedule and run tasks at specific times or at regular intervals. The concept is similar to how the Windows Task Scheduler or the cron jobs in Unix work. The task could be anything - running a specific function, scraping a web page, getting system stats, sending email reminders - anything that your Python application needs to do autonomously at specific times or intervals.

When you are answering this question, keep the following key points in mind:

  1. The most basic scheduler can be designed using Python's built-in time or threading library.
  2. However, for more complex schedules, third-party libraries like schedule or APScheduler are available.
  3. Your design should be simple yet accommodating of extensions when needed for future development.
  4. Make your code readable and understandable, with proper function names and comments.

Answer Example 1

Python's built-in time library can be used for simple scheduling tasks, where tasks need to be performed on certain fixed interval.

import time

def task():
    print("Task completed.")

while True:
    # Call task every 60 seconds
    task()
    time.sleep(60)

In the given code, a function called task is defined which prints "Task completed." This function is called every 60 seconds. The time.sleep() function makes the program wait for the specified amount of seconds (60 in this case).

However, keep in mind that this approach is barebones and basic, and may not fit the needs of complex tasks such as running tasks on specific calendar dates or time of day.

Answer Example 2

A more robust approach would be to use a dedicated scheduler library like APScheduler, which provides a wealth of useful features and flexibility:

from apscheduler.schedulers.background import BackgroundScheduler

def task():
    print("Task completed.")

scheduler = BackgroundScheduler()
scheduler.add_job(task, 'interval', seconds=60)
scheduler.start()

In this code, a function named task is scheduled to run every 60 seconds. The BackgroundScheduler class is used which allows the scheduling to run in the background as a separate thread so it doesn't affect your main application. scheduler.add_job method is used to add a new job to the scheduler.

Beyond this, APScheduler also provides ways to schedule tasks at specific times of day, specific calendar dates, even using cron-like syntax, and manages execution in a robust and fail-safe manner.

More Questions

Question Quick Reference by Category: