Design a task scheduler in Python.
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:
- The most basic scheduler can be designed using Python's built-in
time
orthreading
library. - However, for more complex schedules, third-party libraries like
schedule
orAPScheduler
are available. - Your design should be simple yet accommodating of extensions when needed for future development.
- 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
- How do you troubleshoot bugs in your code?
- Find the distance between two points in 3D space.
- If you were the PM for the fundraising product on FB, what goals would you set?
- You are the PM for Uber when it was only a ride hailing app. Would you expand into Uber Eats? (Trade-off Question)
- Tell me about your experience with natural language processing.