54 lines
1.5 KiB
Python
54 lines
1.5 KiB
Python
import threading
|
|
import time
|
|
|
|
class Scheduler:
|
|
def __init__(self):
|
|
self.tasks = {}
|
|
|
|
def add_task(self, task_name, function, interval):
|
|
"""
|
|
Adds a new task to the scheduler.
|
|
|
|
Parameters:
|
|
task_name (str): Unique name for the task.
|
|
function (callable): The function to run for this task.
|
|
interval (int): Time in seconds between each execution of the task.
|
|
"""
|
|
task = {
|
|
"interval": interval,
|
|
"function": function,
|
|
"stop_event": threading.Event(),
|
|
"thread": threading.Thread(target=self.run_task, args=(task_name,), daemon=True)
|
|
}
|
|
self.tasks[task_name] = task
|
|
task["thread"].start()
|
|
|
|
def run_task(self, task_name):
|
|
"""
|
|
Executes the task in a loop until its stop event is set.
|
|
|
|
Parameters:
|
|
task_name (str): The name of the task to run.
|
|
"""
|
|
task = self.tasks[task_name]
|
|
while not task["stop_event"].is_set():
|
|
task["function"]()
|
|
task["stop_event"].wait(task["interval"])
|
|
|
|
def stop_task(self, task_name):
|
|
"""
|
|
Stops the specified task.
|
|
|
|
Parameters:
|
|
task_name (str): The name of the task to stop.
|
|
"""
|
|
if task_name in self.tasks:
|
|
self.tasks[task_name]["stop_event"].set()
|
|
|
|
def stop_all_tasks(self):
|
|
"""
|
|
Stops all tasks managed by the scheduler.
|
|
"""
|
|
for task_name in self.tasks.keys():
|
|
self.stop_task(task_name)
|