-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.py
54 lines (38 loc) · 1.35 KB
/
scheduler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import time
import random
from datetime import datetime
from db import Task, db
import threading
from tasks import calculate_next_execution_time
def execute_task(task):
task_id, task_name = task.id, task.name
print(f"Executing Task {task_id}: {task_name}", flush=True)
with db.atomic():
task = Task.get_by_id(task.id)
task.status = 'running'
task.save()
time.sleep(random.randint(1, 10))
print(f"Task {task_id}: {task_name} completed", flush=True)
if task.cron_schedule:
task.execution_time = calculate_next_execution_time(task.cron_schedule)
task.status = 'pending'
with db.atomic():
task.save()
print(f"Next occurrence scheduled at {task.execution_time}", flush=True)
else:
with db.atomic():
task = Task.get_by_id(task.id)
task.status = 'completed'
task.save()
def task_scheduler():
while True:
current_time = datetime.now()
tasks_to_execute = Task.select().where(Task.execution_time <= current_time, Task.status == 'pending')
threads = []
for task in tasks_to_execute:
thread = threading.Thread(target=execute_task, args=(task,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
time.sleep(1)