You can download this code by clicking the button below.
This code is now available for download.
This code defines a function named `schedule_task` that takes the interval for task execution and the task function to be executed as parameters. It uses the Schedule library to schedule the task and ensures that the task is executed after the specified time interval.
Technology Stack : Schedule, datetime
Code Type : The type of code
Code Difficulty : Intermediate
from schedule import every, repeat, run_pending, sleep
from datetime import datetime, timedelta
def schedule_task(interval, task_func):
"""
Schedules a task to run at a specified interval using the Schedule library.
Args:
interval (int): The interval in minutes after which the task should be repeated.
task_func (function): The function to be executed at the specified interval.
"""
# Schedule the task to run every 'interval' minutes
every(interval, repeat, task_func, now=datetime.now())
# Run any pending tasks immediately
run_pending()
# Sleep for a bit to avoid a busy loop
sleep(1)
# Example task function
def print_current_time():
print("Current time:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# Example usage
def main():
# Schedule the task to run every 5 minutes
schedule_task(5, print_current_time)
if __name__ == "__main__":
main()