We can store in the job:
priority (original) and last_aging_time?
But note: if we change the priority, we need to re-heapify. Since we are using a heap, we can do:
We can use a heap of tuples: (effective_priority, job_id, job)
How to update the effective_priority?
We need to know when the job was inserted and the current time.
Alternatively, we can have a background thread that ages jobs in the ready queue.
Steps for aging:
Every X seconds, we go through the ready queue and for each job that has been waiting for more than Y seconds, we increase its priority by 1 (or decrease by 1?).
But note: our heap is by priority (lower number is higher). So if we want to make a low priority job (say 10) become higher, we change it to 9.
However, changing the priority of an element in a heap is not straightforward. We can't efficiently update an element in the middle.
So we can do:
We can pop all jobs, adjust their priorities, and then push them back? That's O(n) and might be heavy.
Alternatively, we can use a different data structure: a priority queue that supports updating priorities (like a heap with a hash table for positions). But Python's heapq doesn't support that.
We can implement our own heap with a dictionary to track positions? That's complex.
Another idea: use multiple priority queues (one for each priority level) and then use a round-robin or aging between them.
Let's do:
We have a list of deques (or lists) for each priority level (say 0 to 10, 0 highest).
We also have a current_priority pointer that starts at 0 and cycles through, but if a queue is empty we move to next.
But then how do we prevent starvation? We can increase the priority of jobs in lower queues by moving them to higher queues after a timeout.
We can have:
queues = [deque() for _ in range(11)] # 0 to 10
When adding a job, we put it in the queue for its priority.
Then, we have a scheduler that runs:
while True:
# check if current priority queue has job, if yes run one job from it.
# then move to next priority (with wrap around? or always start from 0? but then low priority jobs starve)
# Instead, we can do: start from 0, if 0 is empty, then 1, etc. until we find a non-empty. Then we run one job and then set current to the next priority (so we don't starve any priority level?).
# But this is round-robin by priority? Actually, if we run one job from priority 0, then next time we start from 1, then 2, etc. This ensures that if there are jobs in priority 1, they will get a chance.
# However, if there are always jobs in priority 0, then priority 1 might starve.
So we need aging: if a job has been in a queue for more than T, we move it to a higher priority queue.
We can do:
For each job, we have a timestamp when it was enqueued.
When we are about to run a job from a queue, we check the timestamp of the job at the front. If it's too old, we move it to a higher priority queue (and update its priority).
But note: we are using multiple queues, so moving from one queue to another is O(1) if we use deque.
However, the problem says "priority queues" (plural) so maybe we are allowed to have multiple.
Let's design with multiple queues and aging:
We have:
queues: list of deques, index 0 is highest priority.
job_metadata: dict job_id -> (priority, enqueue_time, job)
When adding a job:
enqueue it in queues[priority], and record its enqueue_time.
When running:
We start from current_priority (initially 0) and look for the first non-empty queue from current_priority to the end.
Then we take the first job from that queue, and then set current_priority to (current_priority+1) % num_priorities?
But we want to prevent starvation: we want to give lower priorities a chance. So we can set current_priority to the priority we just ran? That would starve lower ones.
Alternatively, we can do:
We try from 0 to max_priority. When we find a non-empty, we run one job and then set current_priority to the next priority (so we cycle through).
But if we have 3 queues:
current_priority=0, queue0 has jobs -> run one from 0, then current_priority=1.
then queue1 is empty, so we go to 2, if 2 has job, run from 2, then current_priority=0?
But then if 0 is always non-empty, we will keep running from 0 and 2, but 1 will starve.
So we need to ensure that we don't skip a priority level if it has jobs that are waiting too long.
We can do aging during enqueue? Or during the run?
Let's do:
We have a function that ages jobs: for each queue from low to high, we take the front job and if it's too old, we move it to the next higher queue.
But note: if we move a job from queue 5 to 4, then we are increasing its priority. But we are only moving the front? What about the ones behind? They might be older too.
Alternatively, we can age all jobs in a queue: for queue i (i>0), if the job at the front has been waiting for more than T, we move it to queue i-1?
But we are increasing priority by moving to a lower index (0 is highest). So if a job is in queue 5, and it's been waiting for T, we move it to queue 4 (which is higher priority than 5? Actually, 4 is higher than 5 because 0 is highest).
Wait, our indexing: 0 is highest, 10 is lowest. So moving from 5 to 4 is increasing priority (making it run sooner). That's good.
So aging: for each queue from lowest to highest (from 10 to 0?), we check the front job of each queue (except queue0) and if it's been waiting for more than T, we move it to the previous queue (i-1).
But note: if we move from queue5 to 4, then the job that was at the front of queue5 is now at the back of queue4? Or we want to put it at the front of queue4?
We want to give it higher priority, so we should put it at the front of queue4? But then we are breaking FIFO within the same priority?
We have two choices:
Option 1: Within the same priority, we do FIFO. Then when we age a job, we move it to the front of the higher priority queue? That would be unfair to jobs that were already waiting in that higher queue.
Option 2: We don't care about FIFO within the same priority, only by priority. Then we can put the aged job at the front of the higher queue?
But note: if we age a job, we want it to run as soon as possible in the higher priority, but not necessarily before other jobs that have been waiting in that higher priority for a long time?
Actually, we want to prevent starvation, so we want to eventually run every job. So if we move a job from a lower priority to a higher, it should run before the jobs that are in the higher priority but arrived later?
However, we are using multiple queues and we are doing round-robin by priority?
This is getting complex.
Alternatively, we can use a single priority queue and adjust the priority of waiting jobs by:
effective_priority = original_priority + aging_factor * waiting_time
But then we need to update the priority of jobs in the heap, which is not supported.
Given the time, let's stick to multiple queues and do:
We have N priority levels (0 to N-1, 0 highest).
We have a list of deques: queues[0..N-1]
We also have a current_priority pointer, which is the next priority we will try to run from.
The run loop:
while True:
# First, age jobs: from lowest priority to highest (from N-1 down to 1) check the front of each queue, if waiting time > threshold, move to the previous queue (higher priority) and put at the front?
# But note: if we move to the front, then it will be the next one to run in that queue. That might be okay.
# Alternatively, we can age by moving the job to the higher queue and then in that queue we do FIFO? Then we put at the back?
# Let's decide: we want to give the aged job a boost, but not necessarily run before all jobs in the higher queue?
# Actually, we want to run it as soon as possible, but we also want to be fair to jobs that have been waiting in the higher queue.
# How about: when we age, we move the job to the higher queue and put it at the front? Then it will run before any job that was already in that higher queue?
# That might be acceptable because the job has been waiting for a long time.
# But then a job that just arrived in the higher queue might have to wait for this aged job? That's okay because the aged job has been waiting longer.
# So: when aging, we move the job from queue[i] to queue[i-1] and insert at the front of queue[i-1].
# Then, we run jobs:
# We start from current_priority and look for the first non-empty queue from current_priority to 0?
# Wait, we want to run the highest priority first? But we are doing round-robin?
# Actually, we want to run the highest priority that has jobs, but then we want to rotate to give lower priorities a chance.
# So we can do:
start = current_priority
while True:
if any(queue from start to 0 is non-empty):
find the first non-empty queue from 0 to start?
This is confusing.
Let's change: we always try to run from the highest priority (0) first, but if we run a job from priority p, then next time we start from p+1?
But then if we run a job from 0, next we try 1, then 2, etc. until we find a non-empty. Then we run from that and set current_priority to that priority?
Example:
queues:
0: [a, b]
1: [c]
2: [d, e]
current_priority=0: we run a (from 0), then current_priority=1.
then we look from 1: queue1 has c, run c, current_priority=2.
then from 2: run d, current_priority=0? (if we wrap) or 3?
If we set current_priority to the next after the one we ran, then after 2 we set to 3 (which is out of range, so wrap to 0). Then next we run b from 0, then current_priority=1.
Then queue1 is empty, so we go to 2 and run e, then current_priority=0?
This way, we are cycling through priorities, but we always run the highest available priority in the current cycle?
Actually, the above: we are not necessarily running the highest priority because we are starting from current_priority and going up until we find a non-empty?
But in the example, after running a (0) and then c (1) and then d (2), we set current_priority to 0? Then we run b (0) and then we set to 1, then 1 is empty, then we go to 2 and run e.
This is okay, but note: after running d (2) we set to 0, then we run b (0) and then set to 1. So we are not giving priority 2 a chance until we cycle through 0 and 1.
But that's the point: we are rotating to prevent starvation.
However, we also have aging: if a job in queue2 has been waiting for more than T, we move it to queue1. Then when we get to queue1, we run it.
This seems workable.
Steps:
Let N be the number of priority levels.
We have:
queues = [deque() for _ in range(N)]
current_priority = 0 # the next priority to try (from 0 to N-1, then wrap)
Aging:
for i in range(N-1, 0, -1): # from N-1 down to 1
if queues[i] and (current_time - queues[i][0].enqueue_time) > AGING_THRESHOLD:
job = queues[i].popleft()
job.priority = i-1 # increase priority (lower number)
job.enqueue_time = current_time # reset the wait time? or keep the original?
# We want to reset the wait time for the new priority?
# Actually, we are moving it to a higher priority, so we want to consider its wait time from when it was in the lower priority?
# But now it's in a higher priority, so we don't want to age it too quickly again?
# Let's reset the enqueue_time to now, so it has to wait again in the higher priority.
queues[i-1].appendleft(job) # put at front so it runs soon in the higher priority.
Running:
for i in range(current_priority, N):
if queues[i]:
job = queues[i].popleft()
run_job(job)
current_priority = (i + 1) % N
break
else:
# no job found from current_priority to N-1, then try from 0 to current_priority-1?
for i in range(0, current_priority):
if queues[i]:
job = queues[i].popleft()
run_job(job)
current_priority = (i + 1) % N
break
This is a bit messy.
Alternatively, we can always start from 0 and go up to N-1, but then we are always giving priority 0 the first chance. That's not round-robin.
We want to rotate the starting point.
Let's change: we start from current_priority and go up to N-1, then from 0 to current_priority-1.
But then if current_priority is 0, we check 0 to N-1. That's the same as always starting from 0?
Actually, if we set current_priority to the next priority after the one we ran, then after running a job from priority i, we set current_priority to i+1. Then next time we start from i+1.
Example:
Initially current_priority=0.
We run from 0 (if available) and set to 1.
Then next time we start from 1, then 2, ... until we wrap.
This way, if there are always jobs in 0, we will run 0 only once every N runs?
But note: when we age, we might move jobs from lower to higher, so then we might have jobs in 0 again.
However, in the running loop, we are doing:
for i in range(current_priority, N):
if queues[i]:
run one job and set current_priority = (i+1) % N
break
else:
for i in range(0, current_priority):
... same ...
This will run the first non-empty queue starting from current_priority. Then set current_priority to the next after that.
This is a round-robin over the priorities, but with the twist that we skip empty queues.
This should work.
But note: what if we have a job in priority 0 and current_priority=5? Then we will run the job in 0 only after we check 5..N-1 and then 0..4. That might be a long time if N is large and there are jobs in 5..N-1.
Actually, we want to run the highest priority available, but also prevent starvation. So we are willing to run a lower priority if the higher ones are empty?
But in the above, we are running the first non-empty queue starting from current_priority. That might be a low priority even if there is a job in a higher priority that we skipped because current_priority was high.
Example:
queues:
0: [a]
1: empty
2: [b]
current_priority=2.
We start at 2, find b, run b, set current_priority=3.
Then next time, we start at 3 (which is empty) and then go to 0? Actually, in the else part we check from 0 to current_priority-1 (which is 2). So we check 0, then 1. We find a in 0.
So we run a and set current_priority=1.
Then next time, we start at 1, then 2? But 2 is empty? Then we run from 0?
This seems to work: we are not always running the highest priority, but we are rotating.
But what if we have:
queues:
0: [a]
1: empty
2: [b, c]
current_priority=0: run a, set to 1.
current_priority=1: check 1 (empty), then 2: run b, set to 3.
current_priority=3: check 3..N-1 (empty), then 0: run a? but a is already run?
Wait, we already ran a. So after running a, we removed it. So then:
current_priority=3: check 3..N-1 (empty), then 0: empty, then 1: empty, then 2: run c, set to 3.
So we ran a, then b, then c.
But note: we didn't run a again because it was removed.
This seems okay.
However, we are not necessarily running the highest priority first because we start from current_priority.
But the goal is to prevent starvation, not necessarily to always run the highest priority.
We can adjust: we could also have a rule: if we find a job in a higher priority (lower index) than current_priority, we reset current_priority to that index+1?
But that might break the round-robin.
Given the complexity, let's stick to the above.
Now, for distributed locks: we are in a single node, so we don't need distributed locks. But if we were distributed, we would have multiple schedulers and we need to ensure that only one scheduler runs the job.
In a distributed system, we can have multiple schedulers that all watch the same queues (which are distributed). But then we need to lock when we take a job from the queue to run.
We can use a distributed lock per job? That's heavy.
Alternatively, we can have a single queue per priority that is atomic (like Redis LPOP) and then we don't need a lock because the pop is atomic. But then we have multiple schedulers popping from the same queue, and they might pop the same job?
Actually, if we use a distributed queue that supports atomic pop (like Redis BLPOP), then each scheduler will get a unique job.
But then how do we handle aging? We need to update the priority of jobs in the queue? That's not possible in a simple queue.
So maybe we need a distributed data structure that supports:
- Multiple queues (by priority) that are atomic pop.
- Aging: we need to be able to move a job from one queue to another.
This is getting very complex.
Given the time, I think we are expected to design a single-node scheduler with the features, and mention how we would extend to distributed.
So let's code a single-node scheduler with:
- Multiple priority queues (deques) for ready jobs.
- Delayed jobs: a min-heap (by scheduled_time) for delayed jobs. We have a thread that moves due delayed jobs to the ready queues.
- Aging: as described, we age jobs in the ready queues by moving them to higher priority if they wait too long.
- We'll use a thread pool to run jobs.
We'll simulate distributed locks by not having them, but we can add a lock for the entire scheduler if we want to run multiple schedulers in the same process? That doesn't make sense.
Alternatively, we can design the scheduler to be safe for multiple threads, so we use a lock for the data structures.
Steps:
We have:
self.queues: list of deques
self.delayed_queue: heap of (scheduled_time, job)
self.jobs: dict job_id -> job (for quick lookup, but we might not need if we don't update jobs? We do update when aging and when moving from delayed)
We need a lock for the entire scheduler because we have multiple threads (the run thread, the aging thread, the delayed thread).
We'll have:
- A thread that runs the scheduler (the run loop).
- A thread that processes delayed jobs (every second, check and move due jobs to ready queues).
- Aging is done in the run loop? Or in a separate thread? We can do aging in the run loop, but then if we have many jobs, aging every run might be heavy.
Alternatively, we can do aging in the same thread that runs jobs, but we don't want to age every time we run a job? Maybe every X jobs or every X seconds.
Let's do:
In the run loop, we age the jobs in the ready queues at the beginning of each loop? But then if we have a lot of jobs, aging might take time.
We can do aging in a separate thread that runs every Y seconds.
Given the complexity, let's keep it simple: do aging in the run loop, but only check the front of each queue (lowest priority queues) and age if needed.
Actually, we can age only the front of each queue because if the front is not old, then the ones behind are even newer? Not necessarily: if we have a burst of jobs, the front might be new and the back old.
So we need to age all jobs? That's O(n) per aging.
Alternatively, we can store the jobs in the queues with their enqueue_time and then when we age, we only look at the front? But then if the front is new, we skip the queue? But there might be old jobs behind.
We can do:
For each queue (from lowest to highest), we check the front job. If it's old, we move it to the higher queue. Then we check the next front (which is the next job) and so on until we find a job that is not old.
But note: if we move the front, then the next job becomes the front and might be old too. So we need to keep checking until the front is not old.
This way, we only process the old jobs at the front of each queue. But what about old jobs that are not at the front? They are behind a newer job. Then they will have to wait until the newer job is run or aged?
Actually, if we have a queue: [job1 (new), job2 (old), job3 (old)] and we are aging by checking the front, we see job1 is new, so we don't age any in this queue. Then job2 and job3 will starve.
So we need to traverse the entire queue? That's O(n) and might be heavy.
Alternatively, we can use a priority queue for each priority level that orders by enqueue_time? Then the front is the oldest. But then we are using a deque for FIFO, so the front is the oldest?
Wait, we are using deque and we append at the right and pop from the left? So the front (left) is the oldest?
Actually, if we append jobs as they come, then the leftmost is the oldest. So we are doing FIFO within the same priority?
Then the front is the oldest in that priority queue. So if we age the front and move it, then the next front is the next oldest.
So we can do:
For each queue (from lowest to highest):
while the queue is not empty and (current_time - queue[0].enqueue_time) > AGING_THRESHOLD:
job = queue.popleft()
job.priority = max(0, job.priority-1) # but note: we are moving to a higher priority (lower index). So if job was in queue[i], we move to queue[i-1]. But if i==0, we cannot move.
if job.priority > 0:
queues[job.priority-1].appendleft(job)
else:
# already highest, we can reset its enqueue_time? or leave it?
# We can reset the enqueue_time so it doesn't get aged again immediately?
job.enqueue_time = current_time
queues[0].appendleft(job) # but wait, we are in queue0? Then we don't move, but we reset the time?
But note: if we are in queue0, we don't move, but we reset the enqueue_time? That would prevent it from being aged again?
Actually, we don't want to age jobs in queue0 because they are already highest.
So:
for i in range(N-1, 0, -1): # from N-1 to 1
while queues[i] and (current_time - queues[i][0].enqueue_time) > AGING_THRESHOLD:
job = queues[i].popleft()
job.priority = i-1
job.enqueue_time = current_time # reset the wait time in the new priority
queues[i-1].appendleft(job)
This way, we only age jobs that are at the front of a queue (the oldest in that queue). And we keep doing until the front is not old.
This ensures that the oldest jobs in each queue get aged first.
But note: what if we have a queue with a mix of old and new? We only age the old ones at the front until we hit a new one. Then the old ones behind the new one will not be aged until the new one is run or aged?
Actually, if the front is new, then we break the while for that queue. But the old ones behind are still old, but they are not at the front. They will become front after the new one is run, and then they will be aged.
So this is acceptable.
Now, for delayed jobs:
We have a min-heap of (scheduled_time, job). We have a thread that runs every second and checks the top of the heap. If the scheduled_time <= current_time, we pop and add to the ready queue (with priority? the job has its own priority).
But note: when we add to the ready queue, we set the enqueue_time to now.
Also, we need to handle the case where the delayed job's scheduled_time is in the past? Then we add immediately.
We'll have:
def _process_delayed_jobs(self):
now = time.time()
while self.delayed_queue and self.delayed_queue[0][0] <= now:
scheduled_time, job = heapq.heappop(self.delayed_queue)
# add to ready queue
job.enqueue_time = now
self._add_to_ready_queue(job)
_add_to_ready_queue(job):
# job has priority and enqueue_time
self.queues[job.priority].append(job)
But note: the job might have been created with a priority, but we might have aged it? No, aging only applies to jobs in the ready queue.
Now, for distributed locks: we are not in a distributed system, so we skip.
But if we were, we would have:
- The delayed jobs and ready queues would be in a distributed storage (like Redis).
- The scheduler would acquire a lock (using a distributed lock service) before processing jobs to ensure only one scheduler is active at a time?
- Or we would have multiple schedulers that all try to pop jobs from the distributed queue, and the queue is atomic so only one gets each job.
We can simulate by having a lock for the entire scheduler (for the single node) to make it thread-safe.
So we'll add a threading.Lock for the scheduler's data structures.
Steps:
We'll have:
self.lock = threading.Lock()
In every method that accesses the queues, we acquire the lock.
But note: the run loop and the delayed thread both access the queues.
We'll do:
with self.lock:
... access queues ...
Now, code structure:
class Job:
def __init__(self, job_id, priority, scheduled_time, function, args, kwargs):
self.job_id = job_id
self.priority = priority
self.scheduled_time = scheduled_time # for delayed jobs, in seconds from now? or absolute time?
self.function = function
self.args = args
self.kwargs = kwargs
self.enqueue_time = None # set when added to ready queue
class Scheduler:
def __init__(self, num_priorities=10, aging_threshold=60):
self.num_priorities = num_priorities
self.queues = [deque() for _ in range(num_priorities)]
self.delayed_queue = [] # heap
self.jobs = {} # job_id -> job (optional, we might not need if we don't update by id)
self.lock = threading.Lock()
self.aging_threshold = aging_threshold
self.current_priority = 0
self.thread_pool = ThreadPoolExecutor(max_workers=5) # or as configurable
def add_job(self, job, delay_seconds=0):
with self.lock:
if delay_seconds > 0:
job.scheduled_time = time.time() + delay_seconds
heapq.heappush(self.delayed_queue, (job.scheduled_time, job))
else:
job.enqueue_time = time.time()
self._add_to_ready_queue(job)
def _add_to_ready_queue(self, job):
# clamp priority to [0, num_priorities-1]
priority = max(0, min(job.priority, self.num_priorities-1))
self.queues[priority].append(job)
def _process_delayed_jobs(self):
now = time.time()
while self.delayed_queue and self.delayed_queue[0][0] <= now:
scheduled_time, job = heapq.heappop(self.delayed_queue)
job.enqueue_time = now
self._add_to_ready_queue(job)
def _age_jobs(self):
now = time.time()
for i in range(self.num_priorities-1, 0, -1):
while self.queues[i] and (now - self.queues[i][0].enqueue_time) > self.aging_threshold:
job = self.queues[i].popleft()
job.priority = i-1
job.enqueue_time = now
self.queues[i-1].appendleft(job)
def _run_ready_jobs(self):
# We try to run one job per cycle? Or multiple?
# Let's run as many as we can until we hit a limit? Or just one and then let the loop continue?
# We'll run one job per cycle and then yield.
# But we have a thread pool, so we can submit multiple jobs?
# We'll run up to a certain number of jobs per cycle?
# Alternatively, we can run all jobs that are ready? But then we might run too many and starve the delayed processing.
# Let's run one job at a time and then re-check delayed jobs and age.
# But note: we are in a loop, so we will eventually run all.
# However, if we have a lot of jobs, we might want to run multiple in one cycle.
# We'll run up to 10 jobs per cycle?
for _ in range(10):
# Find the next job to run
found = False
for i in range(self.current_priority, self.num_priorities):
if self.queues[i]:
job = self.queues[i].popleft()
self.thread_pool.submit(self._execute_job, job)
self.current_priority = (i + 1) % self.num_priorities
found = True
break
if not found:
for i in range(0, self.current_priority):
if self.queues[i]:
job = self.queues[i].popleft()
self.thread_pool.submit(self._execute_job, job)
self.current_priority = (i + 1) % self.num_priorities
found = True
break
if not found:
break # no jobs
def _execute_job(self, job):
try:
job.function(*job.args, **job.kwargs)
except Exception as e:
# log error
pass
def run(self):
while True:
with self.lock:
self._process_delayed_jobs()
self._age_jobs()
self._run_ready_jobs()
time.sleep(0.1) # sleep a bit to avoid busy wait
This is a basic design.
However, note: the _run_ready_jobs runs up to 10 jobs per cycle, but we are submitting them to a thread pool. We might run more than 10 if the thread pool has more workers?
We are submitting 10 jobs and then exiting the loop. Then we sleep. Then next cycle we do again.
But the thread pool might have more jobs running concurrently.
Also, we are not handling job completion? We are just submitting and forgetting.
We might want to handle failures and retries? Not in scope.
Now, distributed: we would replace the in-memory queues with distributed queues (like Redis lists for each priority, and a sorted set for delayed). And we would use a distributed lock to ensure only one scheduler is active at a time?
But if we have multiple schedulers, they would all try to pop from the same distributed queue. We can use Redis RPOPLPUSH for a safe pop? Or use a lock per job?
Alternatively, we can use a single scheduler that holds a lock and then processes jobs. Then we have a leader election.
Given the complexity, we'll leave it at that.
Let's code accordingly.
Note: This is a simplified version for demonstration.
We'll also need to handle shutdown gracefully.
We'll add a stop event.
Let's code accordingly.</think>
import asyncio
import heapq
import time
import uuid
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple
from enum import Enum
import logging
from datetime import datetime, timedelta
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class JobStatus(Enum):
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
@dataclass(order=True)
class ScheduledJob:
"""Heap-ordered job for priority queue"""
priority: int
scheduled_time: float
job_id: str = field(compare=False)
func: Callable = field(compare=False)
args: tuple = field(compare=False)
kwargs: dict = field(compare=False)
created_at: float = field(compare=False)
timeout: Optional[float] = field(compare=False, default=None)
max_retries: int = field(compare=False, default=0)
retry_count: int = field(compare=False, default=0)
backoff_factor: float = field(compare=False, default=1.0)
dependencies: List[str] = field(compare=False, default_factory=list)
status: JobStatus = field(compare=False, default=JobStatus.PENDING)
last_run: Optional[float] = field(compare=False, default=None)
worker_id: Optional[str] = field(compare=False, default=None)
metadata: Dict[str, Any] = field(compare=False, default_factory=dict)
class DistributedLockManager:
"""Manages distributed locks using Redis (or other backend)"""
def __init__(self, redis_client=None, lock_timeout: int = 30):
self.redis = redis_client
self.lock_timeout = lock_timeout
self.local_locks = {} # Fallback for single-node
self.lock_holders = defaultdict(set) # Track who holds which locks
async def acquire_lock(self, resource_id: str, worker_id: str,
blocking: bool = True, timeout: int = None) -> bool:
"""Acquire distributed lock"""
timeout = timeout or self.lock_timeout
if self.redis:
# Use Redis for distributed locks
lock_key = f"lock:{resource_id}"
token = f"{worker_id}:{uuid.uuid4()}"
if blocking:
# Block until lock is acquired
while True:
acquired = await self._try_redis_lock(lock_key, token, timeout)
if acquired:
return True
await asyncio.sleep(0.1)
else:
return await self._try_redis_lock(lock_key, token, timeout)
else:
# Local fallback for single-node
if resource_id not in self.local_locks:
self.local_locks[resource_id] = (worker_id, time.time() + timeout)
self.lock_holders[resource_id].add(worker_id)
return True
return False
async def _try_redis_lock(self, lock_key: str, token: str, timeout: int) -> bool:
"""Try to acquire Redis lock"""
try:
# Using SETNX with expiration for atomic operation
acquired = await self.redis.set(
lock_key,
token,
nx=True,
ex=timeout
)
if acquired:
self.lock_holders[lock_key].add(token)
return bool(acquired)
except Exception as e:
logger.error(f"Redis lock error: {e}")
return False
async def release_lock(self, resource_id: str, worker_id: str) -> bool:
"""Release distributed lock"""
if self.redis:
lock_key = f"lock:{resource_id}"
token = f"{worker_id}:"
# Lua script for atomic release (only release if token matches)
lua_script = """
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
"""
try:
result = await self.redis.eval(
lua_script,
1,
lock_key,
token
)
if result:
self.lock_holders[lock_key].discard(token)
return bool(result)
except Exception as e:
logger.error(f"Redis unlock error: {e}")
return False
else:
# Local fallback
if resource_id in self.local_locks:
holder, _ = self.local_locks[resource_id]
if holder == worker_id:
del self.local_locks[resource_id]
self.lock_holders[resource_id].discard(worker_id)
return True
return False
async def renew_lock(self, resource_id: str, worker_id: str) -> bool:
"""Renew lock expiration"""
if self.redis:
lock_key = f"lock:{resource_id}"
token = f"{worker_id}:"
# Lua script to extend expiration only if token matches
lua_script = """
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("EXPIRE", KEYS[1], ARGV[2])
else
return 0
end
"""
try:
result = await self.redis.eval(
lua_script,
1,
lock_key,
token,
self.lock_timeout
)
return bool(result)
except Exception as e:
logger.error(f"Redis renew lock error: {e}")
return False
return False
class StarvationPreventionMixin:
"""Mixin to prevent job starvation using priority aging"""
def __init__(self, aging_interval: int = 10, aging_factor: float = 0.1):
self.aging_interval = aging_interval
self.aging_factor = aging_factor
self.job_wait_times: Dict[str, float] = {}
self.aging_task: Optional[asyncio.Task] = None
async def start_aging_monitor(self):
"""Start background task to age priorities"""
self.aging_task = asyncio.create_task(self._aging_loop())
async def stop_aging_monitor(self):
"""Stop aging monitor"""
if self.aging_task:
self.aging_task.cancel()
try:
await self.aging_task
except asyncio.CancelledError:
pass
async def _aging_loop(self):
"""Periodically age waiting jobs"""
while True:
try:
await asyncio.sleep(self.aging_interval)
await self._age_waiting_jobs()
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Aging error: {e}")
async def _age_waiting_jobs(self):
"""Increase priority of long-waiting jobs"""
current_time = time.time()
aged_jobs = []
for job_id, wait_start in self.job_wait_times.items():
wait_time = current_time - wait_start
# Age jobs that have waited longer than threshold
if wait_time > (self.aging_interval * 3):
age_increment = int(wait_time / self.aging_interval) * self.aging_factor
await self._adjust_job_priority(job_id, age_increment)
aged_jobs.append(job_id)
logger.debug(f"Aged job {job_id} by {age_increment} priority points")
# Clean up aged jobs tracking
for job_id in aged_jobs:
self.job_wait_times[job_id] = current_time
async def _adjust_job_priority(self, job_id: str, adjustment: float):
"""Adjust job priority (to be implemented by scheduler)"""
raise NotImplementedError
class DelayedJobManager:
"""Manages delayed/scheduled jobs"""
def __init__(self):
self.delayed_jobs: List[Tuple[float, ScheduledJob]] = [] # Min-heap by scheduled_time
self.delayed_jobs_by_id: Dict[str, ScheduledJob] = {}
def add_delayed_job(self, job: ScheduledJob):
"""Add job to delayed queue"""
heapq.heappush(self.delayed_jobs, (job.scheduled_time, job))
self.delayed_jobs_by_id[job.job_id] = job
def get_ready_jobs(self) -> List[ScheduledJob]:
"""Get all jobs that are ready to run"""
current_time = time.time()
ready_jobs = []
while self.delayed_jobs and self.delayed_jobs[0][0] <= current_time:
_, job = heapq.heappop(self.delayed_jobs)
self.delayed_jobs_by_id.pop(job.job_id, None)
# Reset scheduled_time for ready state
job.scheduled_time = current_time
ready_jobs.append(job)
return ready_jobs
def cancel_delayed_job(self, job_id: str) -> bool:
"""Cancel a delayed job"""
if job_id in self.delayed_jobs_by_id:
job = self.delayed_jobs_by_id[job_id]
# Remove from heap (lazy removal - will be filtered when popped)
self.delayed_jobs_by_id.pop(job_id)
return True
return False
def get_delayed_count(self) -> int:
"""Get count of delayed jobs"""
return len(self.delayed_jobs_by_id)
class RobustScheduler(StarvationPreventionMixin):
"""Main scheduler class with all features"""
def __init__(
self,
max_workers: int = 10,
lock_manager: Optional[DistributedLockManager] = None,
default_timeout: float = 300.0
):
self.max_workers = max_workers
self.lock_manager = lock_manager or DistributedLockManager()
self.default_timeout = default_timeout
# Priority queues (min-heap) - multiple queues for priority levels
self.priority_queues: List[List[ScheduledJob]] = [
[] for _ in range(10) # 0=highest, 9=lowest
]
self.queues_by_id: Dict[str, ScheduledJob] = {}
# Worker management
self.workers: Dict[str, asyncio.Task] = {}
self.worker_load: Dict[str, int] = defaultdict(int)
self.available_workers = asyncio.Semaphore(max_workers)
# Job tracking
self.jobs: Dict[str, ScheduledJob] = {}
self.job_results: Dict[str, Any] = {}
self.job_errors: Dict[str, Exception] = {}
# Delayed jobs manager
self.delayed_manager = DelayedJobManager()
# Running state
self.running = False
self.scheduler_task: Optional[asyncio.Task] = None
# Initialize starvation prevention
StarvationPreventionMixin.__init__(self)
logger.info(f"Initialized scheduler with {max_workers} workers")
async def start(self):
"""Start the scheduler"""
self.running = True
# Start aging monitor
await self.start_aging_monitor()
# Start main scheduler loop
self.scheduler_task = asyncio.create_task(self._scheduler_loop())
# Start delayed job processor
asyncio.create_task(self._process_delayed_jobs())
logger.info("Scheduler started")
async def stop(self, graceful: bool = True):
"""Stop the scheduler"""
self.running = False
# Stop aging monitor
await self.stop_aging_monitor()
# Cancel scheduler task
if self.scheduler_task:
self.scheduler_task.cancel()
try:
await self.scheduler_task
except asyncio.CancelledError:
pass
# Wait for workers to complete if graceful
if graceful:
await self._wait_for_workers()
logger.info("Scheduler stopped")
async def schedule(
self,
func: Callable,
*args,
priority: int = 5,
delay_seconds: float = 0,
timeout: Optional[float] = None,
max_retries: int = 0,
backoff_factor: float = 1.0,
dependencies: List[str] = None,
**kwargs
) -> str:
"""Schedule a new job"""
job_id = str(uuid.uuid4())
scheduled_time = time.time() + delay_seconds if delay_seconds > 0 else time.time()
job = ScheduledJob(
priority=min(max(priority, 0), 9), # Clamp to 0-9
scheduled_time=scheduled_time,
job_id=job_id,
func=func,
args=args,
kwargs=kwargs,
created_at=time.time(),
timeout=timeout or self.default_timeout,
max_retries=max_retries,
backoff_factor=backoff_factor,
dependencies=dependencies or []
)
async with self.lock_manager.acquire_async(f"job:{job_id}", f"scheduler:{id(self)}"):
self.jobs[job_id] = job
if delay_seconds > 0:
self.delayed_manager.add_delayed_job(job)
logger.info(f"Scheduled delayed job {job_id} in {delay_seconds}s")
else:
self._add_to_priority_queue(job)
self.job_wait_times[job_id] = time.time()
logger.info(f"Scheduled immediate job {job_id} with priority {priority}")
return job_id
async def schedule_cron(
self,
func: Callable,
cron_expression: str,
*args,
priority: int = 5,
**kwargs
) -> str:
"""Schedule recurring job (simplified - would need cron parser)"""
# In production, use a proper cron library like `croniter`
# This is a simplified version that runs every minute
async def cron_wrapper():
while True:
try:
await func(*args, **kwargs)
except Exception as e:
logger.error(f"Cron job failed: {e}")
await asyncio.sleep(60) # Simple 1-minute interval
return await self.schedule(cron_wrapper, priority=priority, **kwargs)
def _add_to_priority_queue(self, job: ScheduledJob):
"""Add job to appropriate priority queue"""
if job.job_id in self.queues_by_id:
return # Already in queue
self.priority_queues[job.priority].append(job)
self.queues_by_id[job.job_id] = job
heapq.heapify(self.priority_queues[job.priority]) # Re-heapify
async def _scheduler_loop(self):
"""Main scheduler loop"""
while self.running:
try:
# Process any delayed jobs that are ready
ready_jobs = self.delayed_manager.get_ready_jobs()
for job in ready_jobs:
self._add_to_priority_queue(job)
self.job_wait_times[job.job_id] = time.time()
# Try to schedule jobs to workers
await self._dispatch_jobs()
# Check for timed-out jobs
await self._check_timeouts()
# Small sleep to prevent CPU spinning
await asyncio.sleep(0.1)
except Exception as e:
logger.error(f"Scheduler loop error: {e}")
await asyncio.sleep(1)
async def _dispatch_jobs(self):
"""Dispatch jobs to available workers"""
# Get highest priority jobs first
for priority in range(10): # 0=highest to 9=lowest
queue = self.priority_queues[priority]
while queue and self.available_workers.locked() is False:
# Try to acquire worker slot
if await self.available_worker_slot():
job = heapq.heappop(queue)
self.queues_by_id.pop(job.job_id, None)
# Check dependencies
if not await self._check_dependencies(job):
# Re-queue with lower priority temporarily
job.priority = min(9, job.priority + 1)
self._add_to_priority_queue(job)
self.available_workers.release()
continue
# Start job execution
asyncio.create_task(self._execute_job(job))
break
async def _execute_job(self, job: ScheduledJob):
"""Execute a single job"""
worker_id = f"worker-{uuid.uuid4().hex[:8]}"
job.worker_id = worker_id
job.status = JobStatus.RUNNING
job.last_run = time.time()
# Track worker load
self.worker_load[worker_id] += 1
try:
# Acquire resource locks if needed
resource_id = job.metadata.get('resource_id')
if resource_id:
lock_acquired = await self.lock_manager.acquire_lock(
resource_id,
worker_id,
blocking=False
)
if not lock_acquired:
# Re-queue job
job.status = JobStatus.PENDING
self._add_to_priority_queue(job)
self.worker_load[worker_id] -= 1
return
logger.info(f"Executing job {job.job_id} on {worker_id}")
# Run with timeout
result = await asyncio.wait_for(
self._run_job(job),
timeout=job.timeout
)
job.status = JobStatus.COMPLETED
self.job_results[job.job_id] = result
logger.info(f"Job {job.job_id} completed successfully")
except asyncio.TimeoutError:
job.status = JobStatus.FAILED
error = TimeoutError(f"Job timed out after {job.timeout}s")
self.job_errors[job.job_id] = error
logger.error(f"Job {job.job_id} timed out")
if job.retry_count < job.max_retries:
await self._retry_job(job)
except Exception as e:
job.status = JobStatus.FAILED
self.job_errors[job.job_id] = e
logger.error(f"Job {job.job_id} failed: {e}")
if job.retry_count < job.max_retries:
await self._retry_job(job)
finally:
# Release locks
if resource_id:
await self.lock_manager.release_lock(resource_id, worker_id)
# Clean up worker
self.worker_load[worker_id] -= 1
if self.worker_load[worker_id] <= 0:
self.workers.pop(worker_id, None)
async def _run_job(self, job: ScheduledJob):
"""Run the actual job function"""
if asyncio.iscoroutinefunction(job.func):
return await job.func(*job.args, **job.kwargs)
else:
# Run sync function in thread pool
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None,
lambda: job.func(*job.args, **job.kwargs)
)
async def _retry_job(self, job: ScheduledJob):
"""Retry a failed job with exponential backoff"""
job.retry_count += 1
# Calculate delay with exponential backoff
delay = job.backoff_factor * (2 ** job.retry_count)
logger.info(f"Retrying job {job.job_id} (attempt {job.retry_count}/{job.max_retries}) in {delay}s")
# Re-schedule with adjusted priority (lower priority on retry to avoid flooding)
job.priority = min(9, job.priority + 2)
job.scheduled_time = time.time() + delay
self.delayed_manager.add_delayed_job(job)
async def _check_dependencies(self, job: ScheduledJob) -> bool:
"""Check if all dependencies are completed"""
for dep_id in job.dependencies:
dep_job = self.jobs.get(dep_id)
if not dep_job or dep_job.status != JobStatus.COMPLETED:
return False
return True
async def _check_timeouts(self):
"""Check for jobs that have timed out"""
current_time = time.time()
for job in list(self.jobs.values()):
if job.status == JobStatus.RUNNING:
if job.last_run and (current_time - job.last_run) > job.timeout:
logger.warning(f"Job {job.job_id} exceeded timeout")
job.status = JobStatus.FAILED
async def _process_delayed_jobs(self):
"""Background task to process delayed jobs"""
while self.running:
try:
ready_jobs = self.delayed_manager.get_ready_jobs()
for job in ready_jobs:
self._add_to_priority_queue(job)
self.job_wait_times[job.job_id] = time.time()
await asyncio.sleep(1) # Check every second
except Exception as e:
logger.error(f"Delayed job processor error: {e}")
await asyncio.sleep(5)
async def available_worker_slot(self) -> bool:
"""Check if worker slot is available"""
return len(self.workers) < self.max_workers
async def get_job_status(self, job_id: str) -> Optional[Dict]:
"""Get status of a specific job"""
job = self.jobs.get(job_id)
if not job:
return None
return {
'job_id': job.job_id,
'status': job.status.value,
'priority': job.priority,
'created_at': job.created_at,
'scheduled_time': job.scheduled_time,
'last_run': job.last_run,
'retry_count': job.retry_count,
'worker_id': job.worker_id,
'metadata': job.metadata
}
async def cancel_job(self, job_id: str) -> bool:
"""Cancel a pending or delayed job"""
async with self.lock_manager.acquire_async(f"job:{job_id}", f"scheduler:{id(self)}"):
job = self.jobs.get(job_id)
if not job:
return False
if job.status in [JobStatus.PENDING, JobStatus.RUNNING]:
# Remove from queue if pending
if job_id in self.queues_by_id:
self._remove_from_queue(job)
# Remove from delayed if scheduled
self.delayed_manager.cancel_delayed_job(job_id)
job.status = JobStatus.CANCELLED
logger.info(f"Cancelled job {job_id}")
return True
return False
def _remove_from_queue(self, job: ScheduledJob):
"""Remove job from priority queue"""
if job.job_id in self.queues_by_id:
self.queues_by_id.pop(job.job_id)
# Rebuild heap for this priority level
heapq.heapify(self.priority_queues[job.priority])
async def _adjust_job_priority(self, job_id: str, adjustment: float):
"""Adjust job priority for starvation prevention"""
job = self.jobs.get(job_id)
if job and job.status == JobStatus.PENDING:
old_priority = job.priority
new_priority = max(0, min(9, job.priority - int(adjustment)))
if new_priority != old_priority:
# Remove from old queue
self._remove_from_queue(job)
job.priority = new_priority
# Add to new queue
self._add_to_priority_queue(job)
logger.debug(f"Adjusted job {job_id} priority: {old_priority} -> {new_priority}")
async def _wait_for_workers(self):
"""Wait for all workers to complete"""
while self.workers:
await asyncio.sleep(0.5)
def get_stats(self) -> Dict:
"""Get scheduler statistics"""
stats = {
'total_jobs': len(self.jobs),
'pending': sum(len(q) for q in self.priority_queues),
'delayed': self.delayed_manager.get_delayed_count(),
'running': sum(1 for j in self.jobs.values() if j.status == JobStatus.RUNNING),
'completed': sum(1 for j in self.jobs.values() if j.status == JobStatus.COMPLETED),
'failed': sum(1 for j in self.jobs.values() if j.status == JobStatus.FAILED),
'active_workers': len(self.workers),
'queue_lengths': [len(q) for q in self.priority_queues]
}
return stats
# Example usage
async def example_job(name: str, duration: float = 1.0):
"""Example job function"""
print(f"Starting job {name}")
await asyncio.sleep(duration)
print(f"Completed job {name}")
return f"Result of {name}"
async def example_dependency_job():
"""Job with dependencies"""
print("Running dependency job")
await asyncio.sleep(0.5)
return "Dependency completed"
async def main():
"""Example usage"""
# Create scheduler
scheduler = RobustScheduler(max_workers=3)
try:
# Start scheduler
await scheduler.start()
# Schedule some jobs
job1 = await scheduler.schedule(
example_job,
"High Priority Job",
priority=0,
timeout=5.0,
max_retries=2
)
job2 = await scheduler.schedule(
example_job,
"Medium Job",
priority=5,
delay_seconds=2.0
)
job3 = await scheduler.schedule(
example_job,
"Low Priority Job",
priority=9,
max_retries=1
)
# Job with dependencies
dep_job = await scheduler.schedule(example_dependency_job, priority=0)
dependent_job = await scheduler.schedule(
example_job,
"Dependent Job",
dependencies=[dep_job],
priority=1
)
# Let it run for a while
await asyncio.sleep(10)
# Check status
print("\nJob Status:")
for job_id in [job1, job2, job3, dep_job, dependent_job]:
status = await scheduler.get_job_status(job_id)
print(f" {job_id}: {status}")
# Get stats
print("\nScheduler Stats:", scheduler.get_stats())
# Cancel a job
await scheduler.cancel_job(job3)
# Wait a bit more
await asyncio.sleep(3)
finally:
# Graceful shutdown
await scheduler.stop(graceful=True)
if __name__ == "__main__":
# For Redis distributed lock (uncomment with proper Redis setup)
# import redis.asyncio as redis
# redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
# lock_manager = DistributedLockManager(redis_client)
# scheduler = RobustScheduler(lock_manager=lock_manager)
asyncio.run(main())