We are to plan a deterministic scheduler for cron-like jobs. The requirements are:
Pluggable persistence: We should be able to swap out the storage mechanism (e.g., in-memory, database, file) for job definitions and their state.
Metrics: We should be able to collect and report metrics (e.g., job execution times, success/failure counts) in a pluggable way.
Jitter: We want to add jitter to the job execution times to avoid thundering herd problems.
We are designing a scheduler that can run cron-like jobs (with a cron expression or a fixed schedule). It should be deterministic in the sense that given the same state and time, it will schedule jobs the same way. However, jitter introduces some randomness to spread out the load.
Approach:
We'll have a Scheduler class that holds:
A job store (pluggable persistence) that provides:
List of jobs (with their schedule, next run time, etc.)
Ability to update job state (e.g., last run, next run, status)
A metrics collector (pluggable) that can record events (job start, end, success, failure, etc.)
A clock (to get current time, and for testing we can inject a mock clock)
A jitter strategy (pluggable) that can add a random delay to the scheduled time.
The scheduler will run in a loop (or multiple threads/processes) and at each iteration:
Get current time.
Query the job store for jobs that are due (next_run <= current_time). But note: because of jitter, the actual execution time might be later than the scheduled time.
How to handle jitter?
We don't want to change the stored next_run time because that would make the schedule non-deterministic? Actually, we want the schedule to be deterministic in terms of the intended schedule, but we add jitter at execution time.
Idea:
The job store stores the intended next run time (without jitter).
When the scheduler determines that a job is due (intended_next_run <= current_time), it then applies the jitter to get an actual execution time. But note: if we apply jitter every time we check, we might schedule the same job multiple times?
Alternatively, we can adjust the next run time in the job store by the jitter when we set it. But then the stored next run time would be with jitter? That would break determinism because the jitter is random.
Let me think: We want the schedule to be deterministic in the sense that if we run the scheduler twice with the same state (and same random seed?) we get the same behavior? Not necessarily, because jitter is random by definition.
But the requirement says "deterministic scheduler", meaning that the scheduling logic (without jitter) is deterministic. Jitter is an add-on that introduces randomness to avoid bursts.
So, we can do:
Without jitter, the job would run exactly at the scheduled time.
With jitter, we add a random delay (positive or negative? usually positive to delay) to the scheduled time.
How about:
When we compute the next run time (without jitter) for a job, we store that in the job store. Then, when we are about to run the job, we check: if (current_time >= intended_next_run) then we run it, but we also apply jitter by waiting until (intended_next_run + jitter) if that is in the future? But that would mean we are delaying the execution.
But note: we are in a loop and we might have multiple jobs. We want to spread out the execution of jobs that are due at the same time.
Another idea: when we set the next run time (after a job finishes), we set the intended next run (without jitter) and then we also store the jittered next run? That doesn't sound right.
Let's look at how typical cron with jitter works (like in systemd timers or Kubernetes cron jobs with random delay). They often add a random delay to the start time of the job, but the schedule remains fixed.
Example: A job scheduled to run at 10:00, with jitter of 0-30 minutes, will run between 10:00 and 10:30. The next run is still scheduled for the next day at 10:00 (without jitter). So the jitter is applied per execution.
So in our scheduler:
We have an intended next run time (without jitter) for each job.
When the current time reaches (or passes) the intended next run, we then decide to run the job at (intended next run + jitter_delay). But note: if the jitter_delay is large, we might run the job after the intended next run of another job that is due at the same time? That's okay.
However, we must be careful: if we have two jobs both due at 10:00, and we add jitter, they might run at 10:05 and 10:15. But what if we have a loop that checks every minute? We might see both jobs as due at 10:00, but then we schedule them with jitter. But then at 10:05, we run job1, and at 10:15 job2. But what if the loop runs again at 10:01? We don't want to schedule job1 again because we already scheduled it with jitter?
We need to mark that we have already scheduled the job for this intended run. So we can:
When we decide to run a job (at intended_next_run + jitter), we update the job's state to "scheduled" for this run? But then if the jitter is 5 minutes and the job is due at 10:00, at 10:00 we mark it as scheduled for 10:05. Then at 10:05 we run it. But what if the scheduler crashes after marking as scheduled but before running? We need to handle that.
Alternatively, we can adjust the next run time in the job store by the jitter when we set it? That would mean:
When we finish a job, we compute the next intended run (without jitter) and then we add jitter to get the actual next run time we store. But then the stored next run time is with jitter, and the schedule becomes non-deterministic because the jitter changes the interval? Actually, if we add jitter to the next run time, then the interval between runs becomes variable. But the requirement is for a deterministic scheduler (without jitter) and jitter is an add-on.
Let me clarify: The jitter is meant to spread out the execution of jobs that are scheduled at the same time. It doesn't change the periodicity. So if a job is scheduled every hour, it should run every hour (plus jitter). But if we add jitter to the next run time, then the interval might become, for example, 1 hour and 5 minutes, then 1 hour and 10 minutes, etc. That's acceptable? Actually, that's how jitter is often applied: you add a random delay to each scheduled time.
But note: if we add jitter to the next run time, then the schedule becomes non-deterministic in the sense that the exact times are random. But the intended schedule (without jitter) is still deterministic.
How about:
We store in the job store:
- intended_next_run: the next run time without jitter (deterministic)
- last_run: the last time the job actually ran (with jitter)
Then, when we are checking for due jobs, we check against intended_next_run. But we don't run immediately at intended_next_run, we wait until (intended_next_run + jitter). But then we have to track that we have scheduled this run.
Alternatively, we can compute the actual run time as:
and then set the next intended run based on the schedule (without jitter) after the job finishes? But note: the jitter is per run, so for the next run we will compute a new jitter.
So the process for a job:
Step 1: At time T (current time), we check if T >= intended_next_run. If yes, then we are due.
Step 2: We then compute the jittered run time: run_time = intended_next_run + jitter_delay.
Step 3: If run_time <= current_time, then we can run immediately. Otherwise, we schedule the job to run at run_time (but we don't want to block the scheduler, so we might use a timer or a priority queue of scheduled jobs).
But note: if we have a loop that checks every second, and the jitter is 5 minutes, then we will see the job as due at intended_next_run, but we won't run it until 5 minutes later. In the meantime, we might check again and again and see that it's still due? We don't want to schedule it multiple times.
So we need a way to mark that we have already scheduled this run. We can:
Option 1: When we decide to run a job (because intended_next_run <= current_time and we have computed the jittered time), we update the job's state to "scheduled" and store the scheduled run time (with jitter). Then, when the scheduled time arrives, we run it. But then we need a separate mechanism to run at the scheduled time (like a timer).
Option 2: We don't pre-schedule, but when we are in the loop and we see a job due, we check if we have already scheduled it for this intended run. We can store the last scheduled intended run? Or we can update the intended_next_run to the next one (without jitter) as soon as we schedule the current one? But then if the job fails, we might want to retry?
Let's think about the job lifecycle:
The job has a schedule (cron expression or fixed interval). We compute the next intended run (without jitter) based on the last intended run (or start time) and the schedule.
When we start the scheduler, we load jobs and compute their next intended run.
When a job is due (current_time >= intended_next_run), we then:
a. Compute the jittered run time: run_time = intended_next_run + jitter.
b. If run_time <= current_time, then we run immediately (or as soon as possible). Otherwise, we schedule the job to run at run_time.
c. After we run the job (or schedule it for future run), we update the job's intended_next_run to the next one (without jitter) based on the schedule. But note: if we schedule the job for a future time (because of jitter), we don't want to update the intended_next_run until we actually run the job? Because if we update it now, then the next intended run will be based on the current intended_next_run, which is correct.
But what if the job fails? We might want to retry with a backoff? That's a separate concern.
Let's simplify: We are only concerned with the scheduling (when to run the next time). The jitter is only for the start time of the current run.
So:
We have a job with:
schedule: the cron expression or fixed rate.
intended_next_run: the next time the job should run (without jitter).
last_run: the last time the job actually ran (optional, for metrics).
The scheduler loop:
while running:
now = clock.now()
due_jobs = job_store.get_jobs_with_intended_next_run_before(now)
code
for job in due_jobs:
# We have at least one due job.
# Compute jittered run time.
jitter_delay = jitterstrategy.get_jitter(job) # might depend on job, or just random
run_time = job.intended_next_run + jitter_delay
if run_time <= now:
# Run immediately (or as soon as we can, but we are in a loop so we run now)
execute_job(job)
# After execution, update intended_next_run to the next one (without jitter) based on schedule.
job.intended_next_run = schedule_next(job.schedule, job.intended_next_run)
job_store.update_job(job)
else:
# We schedule the job to run at run_time.
# But we are in a loop that checks every so often? We don't want to wait until run_time in this loop.
# We need a way to run the job at run_time. We can use a priority queue (min-heap) of (run_time, job) and then wait until the next run_time.
# However, note: we might have multiple jobs with the same intended_next_run and different jitter, so we want to run them at their jittered times.
# So we should not run the job now, but schedule it for later.
# But then we must not update the intended_next_run until we actually run the job? Because the next intended run is based on the current intended_next_run (which is the one we just used). So if we schedule for later, we don't update the intended_next_run until we run.
# So in the else branch, we add the job to a pending queue (with run_time) and continue.
# Then, we check the pending queue for jobs that have run_time <= now and run them.
Pluggable persistence:
We define an interface for JobStore:
class JobStore(ABC):
@abstractmethod
def get_due_jobs(self, now: datetime) -> List[Job]:
pass
If we have multiple scheduler instances, we need to make sure that a job is only run by one instance. We can do:
When we get due jobs from the job store, we lock them (so that other instances don't get them). Then we update the intended_next_run and release the lock.
How?
code
In the job store, when we call get_due_jobs(now), we can lock the jobs (e.g., set a locked_by field) and return them. Then when we update, we release the lock. If a scheduler crashes, the lock might be held forever, so we need a way to expire locks.
Alternatively, we can use a distributed queue (like a message queue) for jobs. But the requirement is for a cron-like scheduler, so we want to compute the next run times.
Another approach: use a database with a "claimed" field and a TTL. When we get due jobs, we claim them (set claimed_by and claimed_at). Then we run them and update. If a job is claimed but not updated for a long time, we consider it unclaimed.
But that's a lot of work.
Since the requirement doesn't specify distributed, we'll design for single instance and note that for distributed we need to add locking in the job store.
Putting it all together:
code
We have:
code
- Job:
id: str
schedule: Schedule
intended_next_run: datetime
... other job data (command, args, etc.)
- Schedule interface with next_run(after) -> datetime.
- JobStore interface.
- MetricsCollector interface.
- JitterStrategy interface.
- Clock interface (with now()).
- Scheduler class as above.
We can also have a way to add/remove jobs dynamically.
11. Example of a job:
code
def my_job():
print("Hello")
job = Job(
id="job1",
schedule=CronSchedule("* * * * *"), # every minute
intended_next_run=datetime.now(), # but we should compute the next run from the schedule? Actually, when we create a job, we set the initial intended_next_run (maybe the next run from now). Then the scheduler will update it after each run.
# We also need a way to run the job: a callable.
func=my_job,
args=(),
kwargs={}
)
Then in execute_job, we call job.func(*job.args, **job.kwargs).
12. How to compute the next run for a cron expression? We can use a library like croniter.
The scheduler should be robust: if a job fails, we still update the intended_next_run? Yes, because we want to keep the schedule. But sometimes we might want to retry? That's a separate mechanism (like a retry policy). We can leave that to the job itself or to a wrapper.
We also want to handle long-running jobs? We might want to run jobs in parallel? The current design runs jobs sequentially in the main loop. We can use a thread pool to run jobs asynchronously, but then we have to be careful with the intended_next_run update (we update after the job finishes, regardless of success). We can:
When we run a job, we submit it to a thread pool and then continue the loop. But then we might run the same job again (if it's still due) because we haven't updated the intended_next_run? We update the intended_next_run immediately after we start the job? But then if the job fails, we have already updated the intended_next_run to the next run, so we lost the current run? That's not acceptable.
So we must update the intended_next_run only after the job finishes? But then if the job takes a long time, we might have multiple instances of the same job running? We don't want that.
We can have a lock per job (in-memory) so that we don't run the same job concurrently. But then if the job is due again while it's running, we skip that run? Or we run it again? Usually, cron doesn't run the same job concurrently. So we want to avoid overlapping runs.
How about:
code
- When we decide to run a job (either immediately or scheduled for the future), we mark the job as "running" (in memory) and then when it finishes, we mark it as not running and update the intended_next_run.
But then if the job is due again while it's running, we skip that run? That might be acceptable.
Alternatively, we can have the job store track the last run start time and if the intended_next_run is in the past and the job is still running, we don't run it again? But then we might miss a run if the job takes longer than the interval.
This is a common problem with cron: if a job takes longer than its interval, the next run might be skipped or we might have overlapping runs.
We can have a configuration per job: allow_overlap? If not, then we skip the run if the previous run is still active.
Let's add:
code
code
We design a single-threaded scheduler that runs jobs one by one. We have:
code
- JobStore: pluggable storage.
- MetricsCollector: pluggable metrics.
- JitterStrategy: pluggable jitter.
- Clock: for time.
The scheduler loop:
while running:
now = clock.now()
# Run pending jobs that are due (jittered time <= now)
while pending_queue and pending_queue.peek().run_time <= now:
run_time, job_id = pending_queue.pop()
pending_set.remove(job_id)
job = job_store.get_job(job_id)
execute_job(job, run_time) # this updates job.intended_next_run and job_store
# Get due jobs from job store (intended_next_run <= now) and not in pending_set.
due_jobs = job_store.get_due_jobs(now)
due_jobs = [job for job in due_jobs if job.id not in pending_set]
for job in due_jobs:
jitter_delay = jitter_strategy.get_jitter(job)
run_time = job.intended_next_run + jitter_delay
if run_time <= now:
execute_job(job, run_time)
else:
pending_queue.push((run_time, job.id))
pending_set.add(job_id)
time.sleep(0.1)
We assume that the job store's get_due_jobs is efficient (e.g., uses an index on intended_next_run).
For distributed systems, we need to add locking in the job store when getting due jobs and when updating.
We also assume that the job store's update_job is atomic.
This design is deterministic in the sense that the intended_next_run is deterministic (based on the schedule) and the order of execution is determined by the intended_next_run and the jitter (which is random). But note: the jitter is random, so the exact run times are not deterministic. But the schedule (without jitter) is.
We can make the jitter deterministic by using a seeded random number generator per job? But that's not required.
This should meet the requirements.
16. Code structure:
code
scheduler/
__init__.py
job.py # Job class
schedule.py # Schedule interface and implementations
store.py # JobStore interface and implementations
metrics.py # MetricsCollector interface and implementations
jitter.py # JitterStrategy interface and implementations
clock.py # Clock interface and implementation
scheduler.py # Scheduler class
exceptions.py # Custom exceptions
- We might want to have a way to dynamically add/remove jobs while the scheduler is running.
- We might want to have a way to manually trigger a job.
- We might want to have a way to pause/resume the scheduler.
- We might want to have a way to run jobs in parallel (with a thread pool) and handle overlapping runs.
But these are beyond the scope of the initial plan.
19. Testing:
code
- We can test with a mock clock and a mock job store.
- We can test that jobs are scheduled with jitter and that the intended_next_run is updated correctly.
20. Potential issues:
code
- If the job store's get_due_jobs returns a large number of jobs, we might block the loop for a long time? We can process them in batches.
- The pending_queue might grow if we have many jobs with large jitter? But eventually they will run and be removed.
- The pending_set and pending_queue must be kept in sync. We use a set for quick lookup and a priority queue for ordering.
- The pending_queue is a min-heap. We can use heapq.
This plan should be a good starting point.</think>
I'll design a deterministic cron-like scheduler with pluggable components. Here's a comprehensive architecture:
class DeterministicScheduler:
def _execution_loop(self):
"""Main deterministic scheduling loop"""
while self._running:
with self._condition:
now = self.clock.now()
# 1. Get all due jobs (deterministic query)
due_jobs = self.job_store.get_due_jobs(now)
for job in due_jobs:
# 2. Check if already scheduled/executing
if self._is_job_active(job.id):
continue
# 3. Apply jitter to get actual execution time
actual_time = self.jitter_policy.apply_jitter(
job.next_run, job
)
# 4. Schedule if in future, or execute if due
if actual_time > now:
self._pending_queue.put((actual_time, job.id))
self.metrics.record_job_scheduled(
job.id, job.next_run, actual_time,
actual_time - job.next_run
)
else:
self._schedule_immediate(job)
# 5. Wait until next scheduled time or condition
next_run = self._get_next_scheduled_time()
wait_time = max(0, (next_run - now).total_seconds())
self._condition.wait(timeout=wait_time)
def _schedule_immediate(self, job: Job):
"""Schedule job for immediate execution with locking"""
if not self.job_store.acquire_job_lock(job.id):
return # Another instance is running this job
try:
self.metrics.record_job_start(job.id, job.next_run)
start_time = self.clock.now()
# Submit to thread pool
future = self.thread_pool.submit(self._execute_job, job)
# Schedule next run (deterministic calculation)
next_run = job.schedule.next_run(job.next_run)
self.job_store.update_job_schedule(
job.id, next_run,
last_run=start_time,
status=JobStatus.RUNNING
)
except Exception as e:
self.job_store.release_job_lock(job.id)
raise
6. Job Executor with Retries
python
def _execute_job(self, job: Job):
"""Execute job with retry logic and timeout"""
attempt = 0
max_attempts = job.retry_policy.max_attempts if job.retry_policy else 1
while attempt < max_attempts:
try:
with timeout(job.timeout):
result = job.func(*job.args, **job.kwargs)
self.metrics.record_job_complete(
job.id, job.next_run, True,
self.clock.now() - job.next_run
)
self.job_store.update_job_schedule(
job.id,
job.schedule.next_run(job.next_run),
status=JobStatus.SUCCESS
)
return result
except Exception as e:
attempt += 1
if attempt < max_attempts:
delay = job.retry_policy.get_delay(attempt)
time.sleep(delay.total_seconds())
else:
self.metrics.record_job_failed(
job.id, job.next_run, str(e), attempt
)
self.job_store.update_job_schedule(
job.id,
job.schedule.next_run(job.next_run),
status=JobStatus.FAILED
)
raise
finally:
self.job_store.release_job_lock(job.id)
7. Determinism Guarantees
Time Provider: Abstract Clock interface allows injecting fixed time in tests
Schedule Calculation: Pure functions with no side effects
Jitter: Determined by (job_id, schedule_time, seed) - same inputs → same jitter
Ordering: Priority queue ensures fair ordering when multiple jobs have same scheduled time
Calendar Exclusions: Holidays, maintenance windows
Migrateable: Job migration between schedulers with state sync
This design provides:
✅ Deterministic: Same inputs → same schedule
✅ Pluggable: All components swappable
✅ Production-ready: Locking, retries, timeouts
✅ Testable: Injectible clocks and deterministic jitter
✅ Observable: Rich metrics
✅ Thundering herd protection: Configurable jitter
The core insight is separating intended schedule (deterministic cron) from actual execution time (jittered), while maintaining strict ordering guarantees through priority queues and locks.
This approach requires us to have a pending queue (a priority queue) of (run_time, job). But note: we might have multiple due jobs and we want to run them at their jittered times. So we need to manage two things:
code
- The job store's intended_next_run (which is without jitter) tells us when the job is due (without jitter).
- We then compute a jittered run_time and either run immediately (if jittered time is in the past) or schedule for the future.
But what if we have a job that is due at 10:00, and jitter is 5 minutes, and it's 10:03. Then we schedule it for 10:05. Then at 10:05 we run it. But what if at 10:04 we have another job due at 10:00 with jitter 10 minutes? We schedule it for 10:10. Then at 10:05 we run the first job, and then at 10:10 the second.
However, note: when we run the first job at 10:05, we update its intended_next_run to the next one (without jitter). So the next time we check for due jobs, we will use the new intended_next_run.
But what about the second job? Its intended_next_run is still 10:00 (until we run it). So at 10:10, when we run it, we update its intended_next_run.
This seems okay.
However, we must be careful: when we have a pending job (scheduled for future) and then the scheduler loop runs again and sees that the job is still due (because intended_next_run is still 10:00 and now is 10:06) we don't want to schedule it again. So we need to remove the job from the due list once we have scheduled it (until we run it and update the intended_next_run).
How do we do that?
We can:
code
- When we take a due job and schedule it (with jitter) for the future, we remove it from the job store? Or we mark it as "pending" in the job store? But then if the scheduler crashes, we lose the pending job? We want persistence.
Alternatively, we can have two data structures:
code
- The job store holds the intended_next_run (without jitter) and the last run, etc.
- The scheduler also maintains an in-memory pending queue (priority queue) of (run_time, job_id). When we schedule a job for future, we put it in the pending queue. Then, when the run_time arrives, we run it and then update the job store.
But then if the scheduler crashes, we lose the pending queue. So we need to persist the pending jobs? Or we can recompute from the job store?
Actually, the job store only has the intended_next_run. We don't store the jittered run_time. So if we crash, we lose the jittered schedule? That's acceptable because jitter is random and we can recompute the jitter? But note: if we recompute the jitter, then the same job might get a different jitter after restart, which might break the "deterministic" part?
The requirement says deterministic scheduler, but with jitter. We want the schedule (without jitter) to be deterministic, but the jitter is random. So if we restart, we might get a different jitter for the same intended run? That's acceptable.
However, we might have a situation where a job was due at 10:00, and we computed jitter of 5 minutes and scheduled for 10:05. Then the scheduler crashes at 10:04. When we restart, we see that the job's intended_next_run is 10:00 (because we haven't run it yet). So we will compute a new jitter, say 10 minutes, and schedule for 10:10. But then the job would run at 10:10 instead of 10:05. That's acceptable because the jitter is random and we don't guarantee exactly when it runs, only that it runs around the intended time.
So we don't need to persist the jittered run_time.
Therefore, we can have:
code
- The job store holds the intended_next_run (without jitter) and other job metadata.
- The scheduler has a pending queue (in-memory) of (run_time, job_id). When we are about to run a job, we remove it from the pending queue and run it.
But note: if we have multiple scheduler instances (for high availability), we might run the same job twice? We need to lock the job when we schedule it? That's a distributed systems problem.
Since the requirement says "deterministic scheduler", we might assume a single instance? Or we can use the job store to lock jobs.
Let's assume we are building a single-instance scheduler for now, but with pluggable persistence (so we can use a database that supports locking for multiple instances). But the problem doesn't specify distributed, so we can design for single instance and then the persistence layer can handle locking if needed.
For simplicity, let's design for single instance and note that for multiple instances we need a distributed lock.
So in the single instance:
code
We have:
job_store:
- get_jobs_with_intended_next_run_before(now) -> returns list of jobs that are due (intended_next_run <= now) and not currently pending? Or we don't track pending in the job store?
We have a pending queue (in-memory) that holds the jobs we have scheduled (with jitter) but not yet run.
So when we get due jobs from the job store, we must exclude those that are already in the pending queue? Otherwise, we might schedule the same job multiple times.
So we need to keep track of which jobs are pending. We can have a set of job_ids that are pending.
Steps:
while running:
now = clock.now()
# Get due jobs from job store (intended_next_run <= now) and that are not in pending_set.
due_jobs = job_store.get_jobs_with_intended_next_run_before(now)
due_jobs = [job for job in due_jobs if job.id not in pending_set]
for job in due_jobs:
jitter_delay = jitterstrategy.get_jitter(job)
run_time = job.intended_next_run + jitter_delay
if run_time <= now:
# Run immediately, but we don't want to run in the middle of the loop? We can run now and update.
execute_job(job)
# Update intended_next_run
job.intended_next_run = schedule_next(job.schedule, job.intended_next_run)
job_store.update_job(job)
else:
# Schedule for future
pending_queue.push((run_time, job.id))
pending_set.add(job.id)
# Now, check pending_queue for jobs that are due (run_time <= now)
while pending_queue and pending_queue.peek().run_time <= now:
run_time, job_id = pending_queue.pop()
pending_set.remove(job_id)
job = job_store.get_job(job_id)
execute_job(job)
job.intended_next_run = schedule_next(job.schedule, job.intended_next_run)
job_store.update_job(job)
# Then sleep until the next event (either next due job from job store or next pending job)
But note: the pending_queue might have jobs that are due, and we might also have new due jobs from the job store. We want to run as soon as possible.
We can compute the next time we need to wake up:
next_due = min(
job_store.get_next_intended_next_run(), # the next intended_next_run in the job store (without jitter) that is > now
pending_queue.peek().run_time if pending_queue else infinity
)
But note: the job store might have a job that is due at 10:00, and we are at 10:01, but we haven't checked the job store since 10:00? We are checking in the loop. We can set a timeout for the sleep.
Alternatively, we can use a condition variable or a timer that waits until the next event.
However, we are designing for a loop. We can do:
next_wakeup = min(
job_store.get_next_intended_next_run_after(now), # returns the smallest intended_next_run that is > now, or infinity
pending_queue.peek().run_time if pending_queue else infinity
)
sleep_duration = next_wakeup - now
if sleep_duration > 0:
sleep(sleep_duration)
But note: the job store might not have an efficient way to get the next intended_next_run. We can cache the next intended_next_run? Or we can query for the minimum intended_next_run that is > now.
Since the job store is pluggable, we assume it has a way to get the next due job (or the minimum intended_next_run). But for simplicity, we can just check all jobs? That might be inefficient.
Alternatively, we can maintain a min-heap of (intended_next_run, job_id) for all jobs? But then we have to update it when we update a job's intended_next_run. And we have to remove jobs that are pending?
This is getting complex.
Let's simplify the loop:
code
We don't pre-compute the next wakeup from the job store. Instead, we check the job store every iteration (or every few seconds) and the pending queue is a priority queue that we check for immediate jobs.
We can set the loop to run every second (or a configurable interval) and then:
now = clock.now()
# Step 1: Check pending queue for jobs that are due (run_time <= now) and run them.
while pending_queue and pending_queue.peek().run_time <= now:
... run and update ...
# Step 2: Get due jobs from job store (intended_next_run <= now) and not in pending_set.
due_jobs = job_store.get_jobs_with_intended_next_run_before(now)
due_jobs = [job for job in due_jobs if job.id not in pending_set]
for job in due_jobs:
jitter_delay = jitterstrategy.get_jitter(job)
run_time = job.intended_next_run + jitter_delay
if run_time <= now:
execute_job(job)
job.intended_next_run = schedule_next(job.schedule, job.intended_next_run)
job_store.update_job(job)
else:
pending_queue.push((run_time, job.id))
pending_set.add(job.id)
# Then sleep until the next pending job or until the next check of the job store? We can sleep for a short time (like 1 second) or until the next pending job.
But if we sleep for a fixed interval, we might miss the exact time of a pending job? But we are checking the pending queue at the beginning of the loop, so if we sleep for 1 second, we might run a pending job up to 1 second late. That's acceptable.
Alternatively, we can sleep until the next pending job (if any) or a fixed interval (if no pending jobs). But note: the job store might have a job that is due in 5 minutes, but we don't know until we check. So we can:
next_pending = pending_queue.peek().run_time if pending_queue else None
next_intended = job_store.get_next_intended_next_run_after(now) # this might be expensive
if next_pending and next_intended:
next_wakeup = min(next_pending, next_intended)
elif next_pending:
next_wakeup = next_pending
elif next_intended:
next_wakeup = next_intended
else:
next_wakeup = now + 3600 # arbitrary long time
sleep_duration = next_wakeup - now
if sleep_duration > 0:
sleep(sleep_duration)
But again, the job store might not have an efficient way to get the next intended_next_run. We can assume that the job store can provide that, or we can cache the next intended_next_run by having the job store maintain a priority queue? That might be too much.
Alternatively, we can design the job store interface to have:
get_due_jobs(now) -> returns all jobs with intended_next_run <= now.
and then we don't need to get the next intended_next_run. We just check every loop.
So the loop becomes:
while running:
now = clock.now()
# Run pending jobs that are due
while pending_queue and pending_queue.peek().run_time <= now:
... run and update ...
# Get due jobs (without jitter) from job store, excluding pending ones.
due_jobs = job_store.get_due_jobs(now)
due_jobs = [job for job in due_jobs if job.id not in pending_set]
for job in due_jobs:
jitter_delay = jitterstrategy.get_jitter(job)
run_time = job.intended_next_run + jitter_delay
if run_time <= now:
execute_job(job)
job.intended_next_run = schedule_next(job.schedule, job.intended_next_run)
job_store.update_job(job)
else:
pending_queue.push((run_time, job.id))
pending_set.add(job.id)
# Sleep for a short time to avoid busy wait.
time.sleep(0.1)
This is simpler but might be less efficient if there are many jobs and we are checking the job store every 0.1 seconds.
We can adjust the sleep time based on the next pending job? But we don't know the next pending job until we check the pending_queue. We can:
next_pending = pending_queue.peek().run_time if pending_queue else None
if next_pending:
sleep_duration = min(0.1, next_pending - now)
else:
sleep_duration = 0.1
if sleep_duration > 0:
time.sleep(sleep_duration)
But note: the pending_queue might have a job in 5 minutes, but we don't want to sleep for 5 minutes because there might be a job due in the job store in 1 minute. So we still need to check the job store periodically.
So we can do:
next_pending = pending_queue.peek().run_time if pending_queue else None
next_intended = job_store.get_next_intended_next_run_after(now) # if the job store can provide this efficiently.
if next_pending and next_intended:
next_wakeup = min(next_pending, next_intended)
elif next_pending:
next_wakeup = next_pending
elif next_intended:
next_wakeup = next_intended
else:
next_wakeup = now + 3600
sleep_duration = next_wakeup - now
if sleep_duration > 0:
time.sleep(sleep_duration)
But again, the job store might not have an efficient next_intended. We can assume that the job store is a database and we can query for the minimum intended_next_run that is > now. That might be efficient with an index.
Given the complexity, let's assume the job store provides:
get_due_jobs(now): returns jobs with intended_next_run <= now.
get_min_intended_next_run_after(now): returns the minimum intended_next_run that is > now, or None.
Then we can use that for the sleep.
However, note: when we add a job to the pending queue, we don't update the job store's intended_next_run until we run the job. So the job store's next_intended_next_run might be the same as the current one (for the job that is pending). That's okay because we are excluding pending jobs from the due jobs.
But when we compute the next_wakeup, we are using the job store's next_intended_next_run, which might be for a job that is already pending? That would be incorrect because that job is already scheduled (with jitter) and we don't want to wake up for that job from the job store.
So we must exclude pending jobs from the job store's next_intended_next_run? How?
We can have the job store return the next intended_next_run among jobs that are not pending? But the job store doesn't know about pending_set (which is in-memory). So we cannot.
Alternatively, we can maintain a separate structure for the next intended_next_run of non-pending jobs? That's getting too complex.
Given the time, let's stick to a simpler loop that doesn't try to sleep until the next event, but just checks periodically (every 0.1 seconds) and runs due jobs and pending jobs. This is acceptable for a small number of jobs.
But if we have thousands of jobs, checking every 0.1 seconds might be heavy.
We can adjust: if there are no pending jobs and the next due job is in the future, we can sleep until then. But we don't know the next due job without querying the job store. So we can:
code
due_jobs = job_store.get_due_jobs(now) # returns empty if none due.
if due_jobs is empty and pending_queue is empty:
next_intended = job_store.get_next_intended_next_run_after(now)
if next_intended:
sleep_duration = min(0.1, next_intended - now)
else:
sleep_duration = 0.1
time.sleep(sleep_duration)
But note: we might have pending jobs that are due in the future, so we don't want to sleep until the next intended_next_run if there is a pending job earlier? We already check the pending queue at the beginning of the loop.
So:
code
while running:
now = clock.now()
# Check pending queue and run due pending jobs.
while pending_queue and pending_queue.peek().run_time <= now:
... run ...
# Check job store for due jobs (that are not pending)
due_jobs = job_store.get_due_jobs(now)
due_jobs = [job for job in due_jobs if job.id not in pending_set]
if due_jobs:
for job in due_jobs:
... schedule or run ...
# If we have pending jobs, we want to sleep until the next pending job or a short interval.
# If we don't have pending jobs, we can sleep until the next intended_next_run (from job store) or a short interval.
if pending_queue:
next_pending = pending_queue.peek().run_time
sleep_duration = max(0, next_pending - now)
# But we don't want to sleep too long because we might have due jobs in the job store that we haven't checked?
# We are checking the job store every loop. So we can sleep until the next pending job, but then we might miss a due job from the job store that becomes due before the pending job?
# Actually, if a job becomes due in the job store, we will only see it on the next loop. So if we sleep until the next pending job, and a job becomes due in the job store during that sleep, we will be late.
# So we should not sleep longer than the time until the next due job from the job store? But we don't know that without querying.
# We can query the job store for the next intended_next_run_after(now) and then take the minimum of that and the next pending.
next_intended = job_store.get_next_intended_next_run_after(now)
if next_intended:
next_wakeup = min(next_pending, next_intended)
else:
next_wakeup = next_pending
sleep_duration = max(0, next_wakeup - now)
else:
next_intended = job_store.get_next_intended_next_run_after(now)
if next_intended:
sleep_duration = max(0, next_intended - now)
else:
sleep_duration = 0.1 # arbitrary
if sleep_duration > 0:
time.sleep(sleep_duration)
This is getting complex. Given the time, I propose we start with a simpler approach:
code
We run a loop every 0.1 seconds (or configurable interval) and in each iteration:
now = clock.now()
# Run pending jobs that are due.
while pending_queue and pending_queue.peek().run_time <= now:
run_job_from_pending()
# Get due jobs from job store (intended_next_run <= now) and not in pending_set.
due_jobs = job_store.get_due_jobs(now)
due_jobs = [job for job in due_jobs if job.id not in pending_set]
for job in due_jobs:
jitter_delay = jitterstrategy.get_jitter(job)
run_time = job.intended_next_run + jitter_delay
if run_time <= now:
run_job(job) # which updates intended_next_run and job_store
else:
pending_queue.push((run_time, job.id))
pending_set.add(job.id)
time.sleep(0.1)
This is simple and works for a single instance. For multiple instances, we would need to lock the job when we get it from the job store (so that only one instance runs it). We can have the job store support locking (e.g., using a database row lock) when we get due jobs and update.
But for now, we design for single instance.
def run(self):
while self.running:
now = self.clock.now()
# Run pending jobs that are due.
while self.pending_queue and self.pending_queue.peek()[0] <= now:
run_time, job_id = self.pending_queue.pop()
self.pending_set.remove(job_id)
job = self.job_store.get_job(job_id)
self.execute_job(job, run_time) # run_time is the scheduled time (with jitter)
# Get due jobs from job store (intended_next_run <= now) and not pending.
due_jobs = self.job_store.get_due_jobs(now)
due_jobs = [job for job in due_jobs if job.id not in self.pending_set]
for job in due_jobs:
jitter_delay = self.jitter_strategy.get_jitter(job)
run_time = job.intended_next_run + jitter_delay
if run_time <= now:
self.execute_job(job, run_time)
else:
self.pending_queue.push((run_time, job.id))
self.pending_set.add(job.id)
# Sleep until next event or a short interval.
self.sleep_until_next_event(now)
def execute_job(self, job: Job, run_time: datetime):
# run_time is the scheduled time (with jitter) that we are running at (or after).
# But note: if we are running immediately (run_time <= now), then run_time might be in the past? Actually, we are running at now, but the scheduled time is run_time (which might be in the past). That's okay.
self.metrics.record_job_start(job.id, job.intended_next_run) # intended_next_run is the scheduled time without jitter.
try:
# Actually run the job (call the job's function, etc.)
job.run()
success = True
except Exception as e:
success = False
# log error?
finally:
duration = self.clock.now() - run_time # or from start to end? We should measure from when we started running the job.
self.metrics.record_job_end(job.id, job.intended_next_run, success, duration.total_seconds())
# Update the intended_next_run for the next run.
job.intended_next_run = job.schedule.next_run(job.intended_next_run)
self.job_store.update_job(job)
def sleep_until_next_event(self, now):
# We want to sleep until the next pending job or until the next intended_next_run in the job store (for non-pending jobs) or a short interval.
next_pending = self.pending_queue.peek()[0] if self.pending_queue else None
next_intended = self.job_store.get_next_intended_next_run_after(now)
if next_pending and next_intended:
next_wakeup = min(next_pending, next_intended)
elif next_pending:
next_wakeup = next_pending
elif next_intended:
next_wakeup = next_intended
else:
next_wakeup = now + 3600 # arbitrary
sleep_duration = (next_wakeup - now).total_seconds()
if sleep_duration > 0:
time.sleep(sleep_duration)
However, note: the pending_queue might have a job that is due very soon, but the job store might have a job that is due even sooner? But we are excluding pending jobs from the job store's due jobs, so the next_intended from the job store is for a non-pending job. So we want to wake up at the earliest of the pending job and the next non-pending job's intended_next_run.
But wait: the job store's get_next_intended_next_run_after(now) returns the minimum intended_next_run that is > now, but it might be for a job that is already pending? We don't want that. So we need the job store to return the next intended_next_run for jobs that are not pending? But the job store doesn't know about pending_set.
So we have two options:
Option 1: The job store doesn't provide get_next_intended_next_run_after, and we just sleep for a short interval (like 0.1 seconds) and check every time. This is simpler and works, but might be inefficient if there are many jobs and we are sleeping for 0.1 seconds even when the next event is far away.
Option 2: We maintain a separate min-heap of intended_next_run for non-pending jobs? But then we have to update it when we update a job's intended_next_run and when we add/remove from pending_set.
Given the complexity, let's go with Option 1 for now (fixed sleep interval) and note that for production we might want to optimize.
Alternatively, we can have the job store return the next intended_next_run for jobs that are not in a given set of excluded job ids? But that's not standard.
Since the job store is pluggable, we can design it to have:
But that might be inefficient for the job store to filter.
Let's stick to fixed interval for simplicity.
In the job store, we can have:
- last_run_start: datetime
- last_run_end: datetime
Then, when we are about to run a job, we check if the previous run is still active (if last_run_start and not last_run_end, and current_time - last_run_start < some timeout?) but that's not reliable.
Alternatively, we can have an in-memory set of running jobs. When we start a job, we add its id to running_set. When it finishes, we remove it. Then, when we are about to run a job, if it's in the running_set, we skip.
But then if the scheduler crashes, the running_set is lost and we might run the job again. We can have the job store record the run status? But that's complex.
Given the time, let's assume we run jobs sequentially (no parallel) and we update the intended_next_run only after the job finishes. Then we don't have overlapping runs because we only run one job at a time. But then if a job takes a long time, the next due job might be delayed.
We can run jobs in a thread pool, but we must ensure that we don't run the same job concurrently. We can have a lock per job (in memory) and if the job is already running, we skip the run (and maybe record that we skipped?).
But then if we skip, we don't update the intended_next_run? Then the same job will be due again immediately? That's not good.
We can update the intended_next_run even if we skip? But then we are skipping a run.
This is getting out of scope.
Let's stick to sequential execution for simplicity.