Steps for scheduling a run for a job:
a. Begin transaction.
b. Select the job with FOR UPDATE to lock the row.
c. Check current running runs for this job (count of runs with status 'running' and job_id = ?) and also check pending runs that are due? Actually, we are about to create a pending run. We want to make sure that after creating this run, the total (running + pending) does not exceed max_concurrent? But note: pending runs are not running yet, but they are scheduled. We might want to limit the number of concurrent runs (running) only, and pending runs are just waiting to run? Or we might want to limit the total number of runs (including pending) that are in the system for a job? Typically, we care about concurrent executions, so we only count running.
However, if we have max_concurrent=1 and we schedule a run every minute, but the job takes 2 minutes, then we will have two runs (one running and one pending) and then when the first finishes the second will run. So we allow pending to accumulate? That's acceptable.
So we check: current_running < max_concurrent? Then we can create a new run (with status 'pending').
But what about deduplication? We don't want two runs for the same scheduled time? Actually, if the job is scheduled every minute, and we run the scheduler every minute, we might create a run for the same minute if the previous run is still pending? But that's okay because we are allowed to have multiple pending? However, if the job is idempotent and we want to avoid overlapping runs, then we set max_concurrent=1 and then we won't create a new run until the previous one finishes (or fails and retries). But note: if the job fails and we retry, we create a new run (with status pending) and then when the scheduler runs again, it will see that current_running is 0 (if the previous run has failed and is not running) and then create another run? But we already have a pending run for the retry? So we need to avoid creating a new run for the same scheduled time if there's already a pending run for that job?
Let's clarify: we have a scheduled job that runs every minute. At 10:00, we create a run (run1). If run1 is still running at 10:01, then we don't create a new run because current_running=1 and max_concurrent=1. But if run1 fails at 10:00:30 and we retry (creating run2 at 10:00:30 with status pending and next_retry_at in the future), then at 10:01 the scheduler runs and sees current_running=0 (because run1 is failed and run2 is pending but not running). So it will create run3 for 10:01. That's acceptable because run2 is a retry of run1 and we don't want to miss the 10:01 schedule.
However, if we don't want to have two pending runs (the retry and the new scheduled run) at the same time? That's a design decision. Typically, we want to keep the schedule and retries separate. So we allow both.
But what if the job fails and we set max_retries=0? Then we don't create a retry, so at 10:01 we will create a new run.
So the rule: when scheduling a new run (from the scheduler), we only check the current running runs (status='running') for that job. We don't count pending runs (including retries) because they are not running yet.
However, we also want to avoid creating two runs for the same scheduled time? The scheduler runs every minute, and if it takes more than a minute to process, we might run the same job twice in the same minute? But we are using the next_run column and we update it after creating a run. So we should update next_run only after we have created a run? And we lock the job row so only one scheduler can update at a time.
Steps:
- Start transaction.
- SELECT * FROM jobs WHERE job_id = ? FOR UPDATE.
- Check if next_run <= now. If not, skip.
- Check current_running (SELECT COUNT(*) FROM job_runs WHERE job_id = ? AND status='running') < max_concurrent.
- If yes, create a new run (insert into job_runs with status='pending', scheduled_at = next_run? or we can have a scheduled_at field? and then set next_run for the job to the next scheduled time after the current next_run?).
But note: we are scheduling the next run for the job. We want to set the next_run to the next scheduled time after the current next_run (which is the one we are about to run). So we calculate the next run time from the current next_run (or from now?) using the schedule.
Example: cron every minute. next_run is 10:00. We are at 10:00:05. We schedule a run for 10:00 (with scheduled_at=10:00) and then set next_run to 10:01.
But what if the scheduler runs at 10:00:30? Then we are late for 10:00. We still schedule the run for 10:00? And then set next_run to 10:01. That's acceptable.
However, if we are very late and the next scheduled time (10:01) is already in the past? Then we set next_run to the next future time? We should calculate the next run time after the current time? Actually, we are using next_run to know when to run. So we set next_run to the next scheduled time after the current next_run (which might be in the past if we are late). But then we are scheduling a run for a time in the past? That's okay because we are running now. But we record the scheduled_at as the intended time (10:00) and the actual run time (started_at) will be now.
Alternatively, we can set scheduled_at to the next_run (the intended time) and then set next_run to the next scheduled time after that.
So:
scheduled_at = next_run (the intended time of this run)
then compute next_run = next scheduled time after scheduled_at (using the schedule).
Then update the job's next_run to that.
But what if the job is one-time? Then we set next_run to null and the job won't be scheduled again.
So in the job definition, we have a schedule (cron or interval) and we also have a one-time flag? Or we can have a schedule that is a specific timestamp? We can support:
- cron: standard cron expression.
- interval: every N seconds.
- one-time: a specific timestamp.
We can have a column `schedule_type` and `schedule_value`. For cron, schedule_value is the cron string. For interval, schedule_value is the interval in seconds. For one-time, schedule_value is the timestamp.
Then when we compute next_run, we do:
if schedule_type = 'cron': next_run = next cron time after scheduled_at (or after now? we use the last scheduled time?).
if schedule_type = 'interval': next_run = scheduled_at + interval_seconds.
if schedule_type = 'one-time': next_run = NULL (after running once).
But note: we are storing the next_run in the job. So for interval, we can do:
next_run = last_run_time + interval_seconds? But if the job is delayed, we want to run as soon as possible? Actually, we want to run at fixed intervals from the intended time? Or from the actual start time? This is a design decision.
Typically, cron runs at fixed times, and if you miss one, you skip. For intervals, you might want to run every N seconds from the start of the last run? Or from the intended time? We'll do:
For interval: next_run = last_scheduled_time + interval_seconds.
So we store the last_scheduled_time (the intended time of the last run) and then add interval. That way, if the job takes longer than the interval, we won't schedule a new run until the current one finishes? Because we check current_running? But note: we are scheduling the next run based on the last scheduled time, not the actual start time. So if the job takes 2 minutes and interval is 1 minute, we will schedule the next run at last_scheduled_time+1min, but then when we check current_running, we might have a running job so we won't create the run? Then the next time the scheduler runs, we will see that next_run is in the past and try again. But then we will create a run for the same scheduled time? We are updating next_run only when we create a run? So we might get stuck?
Let's simulate:
Job: interval 1 minute.
At 10:00, we create run1 (scheduled_at=10:00) and set next_run=10:01.
At 10:01, run1 is still running (current_running=1, max_concurrent=1) -> we don't create run2.
At 10:02, run1 is still running? Then we don't create run2 again? But we haven't updated next_run? So next_run is still 10:01. Then at 10:02 we try to schedule, we see next_run=10:01 <= now, and current_running=1 (if run1 is still running) -> we don't create. Then at 10:03, same.
When run1 finishes at 10:05, then at 10:06 the scheduler runs, sees next_run=10:01 <= now, and current_running=0, so it creates run2 with scheduled_at=10:01? But that's in the past. Then we set next_run=10:02? But then we are running an old scheduled time? That might not be what we want.
Alternatively, we can update next_run even if we don't create a run? But then we would skip the 10:01 run? That's also not good.
We want to run every minute, but if a run takes more than a minute, we want to run as soon as the previous run finishes? But then we are not running at fixed intervals.
This is a common problem. We have two strategies:
1. Fixed schedule: run at fixed times, and if a run is still running at the next scheduled time, skip that scheduled time? But then we are missing runs.
2. Fixed delay: run N seconds after the previous run finished? That's more like a queue.
For cron replacement, we usually want fixed schedule. So we accept that if a run takes longer than the interval, we will have overlapping runs? But we have max_concurrent to prevent that. So we set max_concurrent=1 to prevent overlapping, and then we will skip the next scheduled time if the previous one is still running? But then we are missing runs.
Alternatively, we can allow multiple runs (max_concurrent>1) and then we will have overlapping runs? But then we are not running at fixed intervals because we are queueing.
Let's stick to the fixed schedule and allow max_concurrent to control overlapping. So if max_concurrent=1, then we will only have one run at a time, and if a run takes longer than the interval, we will skip the next scheduled time? But then we are not running at fixed intervals.
Actually, with max_concurrent=1, we will not create a new run until the previous one finishes. So the next run will be scheduled for the next scheduled time after the previous one finishes? But we are calculating next_run based on the last scheduled time, not the finish time.
Example:
Schedule: every minute (cron: * * * * *)
At 10:00:00, we create run1 (scheduled_at=10:00) and set next_run=10:01.
run1 takes 2 minutes, finishes at 10:02.
At 10:01, the scheduler runs, sees next_run=10:01 <= now, but current_running=1 (run1 is running) -> doesn't create run2.
At 10:02, the scheduler runs, sees next_run=10:01 <= now, and current_running=0 (run1 finished at 10:02:00? but the scheduler might run at 10:02:05) -> creates run2 with scheduled_at=10:01? That's a run for 10:01 that is being created at 10:02. Then run2 runs at 10:02:05 and finishes at ... Then we set next_run to 10:02? But then we are running 10:01 at 10:02 and then 10:02 at ...? This is messy.
We need to decide: do we want to run exactly at the scheduled time (if possible) or do we want to run as soon as possible after the scheduled time if the previous run is still running?
For cron, we usually want to run at the scheduled time. If the job is still running, we might want to skip that run? Or we might want to run it as soon as the previous run finishes? There's no one answer.
Let's design for the fixed schedule and allow skipping if the job is already running (with max_concurrent=1). But then we are missing runs.
Alternatively, we can have a queue of scheduled runs? But then we are not running at fixed times.
Given the complexity, we might want to break the problem:
We have two concepts:
- Schedule: when the job should be triggered.
- Concurrency: how many instances of the job can run at the same time.
We want to trigger the job at the scheduled time, but if the job is already running (and max_concurrent is reached) then we skip that trigger? Or we queue it? We'll skip by default, but we can have an option to queue? That's getting too complex.
Let's simplify:
We will schedule a run at each scheduled time, but only if the number of currently running runs (for that job) is less than max_concurrent. If not, we skip that scheduled time and move to the next.
Then in the example above:
At 10:00: schedule run1 (scheduled_at=10:00) and set next_run=10:01.
At 10:01: run1 is still running, so we skip 10:01 and set next_run=10:02? But then we are skipping 10:01 and the next run will be at 10:02? But we already have a run for 10:00 that is running. Then at 10:02, run1 is still running? Then skip again? Until run1 finishes. Then at the next scheduler tick after run1 finishes, we will see that next_run is 10:01 (which is in the past) and current_running=0, so we create a run for 10:01? But that's a run for a past time.
We don't want to create runs for past times. We want to run at the scheduled time, and if we miss it, we skip.
So we should not create a run for a scheduled time that is in the past? But then if the scheduler is down for a minute, we miss a run.
We can change: when we schedule a run, we set the run's scheduled_at to the next_run (which is in the future or now). Then we set next_run to the next scheduled time after that. But if the scheduler is down and we wake up at 10:02, then next_run is 10:00? Then we would create a run for 10:00 at 10:02? That's a run for a past time.
We want to run at the scheduled time, so if we are late, we skip that scheduled time and run at the next one.
How about:
When we schedule a run, we set the run's scheduled_at to the next_run (which is the intended time). Then we calculate the next_run as the next scheduled time after the current next_run (which might be in the future). But if the current next_run is in the past, then we set the run's scheduled_at to the current next_run (which is in the past) and then set next_run to the next scheduled time after the current next_run? That would cause the run to be for a past time.
Alternatively, we can set the run's scheduled_at to the current time? But then we are not running at the scheduled time.
We need to decide: is the scheduled time a hard requirement? For cron, yes. So we want to run at 10:00, 10:01, etc. If we are late for 10:00, we run at 10:00 as soon as we can? But then we are running at 10:00:05 and the next run at 10:01:05? That's not exactly on the minute.
Given the complexity, let's assume we are okay with running as soon as possible after the scheduled time, but we record the intended scheduled time. And we don't try to run for past scheduled times if we are too late? We can set a threshold: if the scheduled time is more than X seconds in the past, skip? But then we are missing runs.
Another idea: we store the last scheduled time we attempted (in the job). And then we schedule the next run based on that, regardless of when we actually run. So:
job table: last_scheduled_time (the time we last attempted to schedule a run, i.e., the scheduled time of the last run we created).
Then the scheduler:
For each job, if last_scheduled_time is null, then set last_scheduled_time to the first scheduled time (based on the schedule and the job's creation time? or now?).
Then calculate the next scheduled time after last_scheduled_time.
Then we check if that next scheduled time is <= now? If yes, then we try to create a run with scheduled_at = next scheduled time? But then we are creating a run for a time that might be in the past? But we are using the last_scheduled_time to compute the next, so if we are late, the next scheduled time might be in the past? Then we would create a run for a past time.
Example:
Job created at 10:00 with cron every minute.
last_scheduled_time = null.
We compute the first scheduled time: 10:00 (if we use now) or the next minute? We can use the job creation time? Let's use the job creation time as the start.
So at 10:00:05, we create a run for 10:00 (scheduled_at=10:00) and set last_scheduled_time=10:00.
Then compute next_run: 10:01.
At 10:01, we create a run for 10:01 and set last_scheduled_time=10:01.
If at 10:01 the run is still running (max_concurrent=1), then we don't create a run for 10:01? But we already created it? We are creating the run at the scheduled time? Actually, we are creating the run at the scheduled time? We are triggering at the scheduled time.
But note: the scheduler runs every minute, and at 10:01 it will try to schedule the next run (which is 10:01). But if the 10:00 run is still running, we don't create the 10:01 run? Then we skip 10:01.
Then at 10:02, we compute the next run after last_scheduled_time=10:00? No, we update last_scheduled_time only when we create a run? So if we skipped 10:01, then last_scheduled_time is still 10:00. Then at 10:02, we compute next_run as 10:01 (which is in the past) and then we try to create a run for 10:01? That's a run for a past time.
So we need to update last_scheduled_time even if we don't create a run? Then we would skip 10:01 and set last_scheduled_time=10:01? Then at 10:02, we compute next_run=10:02.
But then we are skipping the 10:01 run.
This is getting very messy.
Given the time, let's simplify the requirements:
We want to schedule jobs at fixed times (cron) or intervals. We want to avoid overlapping runs (by max_concurrent). We want to retry on failure.
We'll design the following:
- The scheduler runs every minute (or more frequently) and for each job, it checks if the job's next_run is <= now.
- If yes, it attempts to create a run (with status pending) for that job, but only if the number of currently running runs (status='running') for that job is less than max_concurrent.
- If it creates a run, then it updates the job's next_run to the next scheduled time (based on the schedule and the current next_run, which is the scheduled time of the run we just created). If the job is one-time, set next_run to null.
- If it doesn't create a run (because of concurrency), then it does not update next_run? Then the next time the scheduler runs, it will see the same next_run and try again? That would cause continuous attempts until the concurrency frees up? But then we are trying to run the same scheduled time multiple times? We don't want that. We want to try only once per scheduled time.
So we should update next_run even if we don't create a run? Then we are skipping that scheduled time.
But then if we skip because of concurrency, we are missing a run? That might be acceptable if the job is long-running and we don't want to overlap.
Alternatively, we can have a queue of scheduled runs? But then we are not running at fixed times.
Let's decide:
We want to run at the scheduled time if possible. If not (because of concurrency), we skip that scheduled time and move to the next.
So:
When the scheduler sees that next_run <= now, it checks concurrency. If it can run, it creates a run and updates next_run to the next scheduled time. If it cannot run (because of concurrency), it updates next_run to the next scheduled time (skipping the current one) and does not create a run.
But then we are skipping a run because of concurrency, which might be what we want.
Example:
Job: cron every minute, max_concurrent=1.
At 10:00: create run1 (scheduled_at=10:00), set next_run=10:01.
At 10:01: run1 is still running -> cannot create run2, so set next_run=10:02 (skipping 10:01).
At 10:02: run1 is still running? Then skip 10:02, set next_run=10:03.
... until run1 finishes. Then at the next scheduler tick, we will see that next_run is in the past (say 10:05) and current_running=0, so we create a run for 10:05? But we skipped 10:01,10:02,10:03,10:04? That's a lot of skipped runs.
That might be acceptable because we don't want to run multiple instances.
But what if the job fails and we retry? Then we have a pending run (retry) that is not running. Then at 10:01, we have run1 failed and a retry pending? Then current_running=0? So we create a new run for 10:01? Then we have two runs: the retry (for 10:00) and the new run for 10:01. That's acceptable.
So the rule: when scheduling a new run (from the scheduler), we only consider runs that are running (not pending) for concurrency. Pending runs (including retries) are not counted because they haven't started.
But then we might have multiple pending runs for the same job? That's acceptable because they will run one after the other (if max_concurrent=1) because when one starts, the others are still pending.
However, we might want to limit the number of pending runs? We don't want an infinite backlog. We can set a max_pending? But that's an extension.
Given the complexity, let's stick to the above.
Steps for the scheduler:
For each job where next_run <= now:
BEGIN TRANSACTION;
SELECT * FROM jobs WHERE job_id = ? FOR UPDATE;
-- Calculate the intended scheduled time for this run: it's the job's next_run.
let intended_scheduled_time = job.next_run;
-- Check current running runs for this job (status='running')
SELECT COUNT(*) FROM job_runs WHERE job_id = ? AND status='running';
IF count < job.max_concurrent THEN
-- Create a new run
INSERT INTO job_runs (job_id, status, scheduled_at, created_at)
VALUES (?, 'pending', intended_scheduled_time, NOW());
-- Then update the job's next_run to the next scheduled time after intended_scheduled_time.
-- If the job is one-time, set next_run to null.
-- Else, compute next_run = next schedule after intended_scheduled_time.
-- We might need a function to compute the next run time given the schedule and the last scheduled time.
UPDATE jobs SET next_run = ? WHERE job_id = ?;
ELSE
-- Skip this scheduled time, update next_run to the next scheduled time after intended_scheduled_time.
UPDATE jobs SET next_run = ? WHERE job_id = ?;
END IF;
COMMIT;
But note: we are updating next_run in both cases. So we are always moving forward.
However, what if the job's schedule is changed? Then we need to recalculate next_run? We can do that when the job is updated.
Also, when a run finishes (or fails and retries), we don't update next_run. The scheduler is the only one that updates next_run.
Now, what about deduplication? We are creating one run per scheduled time, and we are updating next_run so we won't create another run for the same scheduled time. But what if two schedulers run at the same time? We lock the job row, so only one will update.
But what if the job has max_concurrent>1? Then we might create multiple runs for the same scheduled time? Because we check current_running, and if we are below max_concurrent, we create a run. But then we update next_run to the next scheduled time. So if we have max_concurrent=2, and at the scheduled time we have 0 running, we create one run and update next_run to the next scheduled time. Then we don't create a second run for the same scheduled time because we already updated next_run.
So we are creating at most one run per scheduled time, regardless of max_concurrent? That's not what we want. We want to be able to have multiple runs for the same scheduled time if max_concurrent>1? But then we are creating multiple runs at the same scheduled time? That's not typical for cron. Cron runs once per scheduled time.
Actually, for cron, we want one run per scheduled time. But if the job takes longer than the interval, we might want to run multiple instances? That's why we have max_concurrent. But the scheduled time is the time we trigger the job. If we trigger at 10:00 and the job takes 2 minutes, then at 10:01 we don't trigger again because we are already at max_concurrent=1? But if max_concurrent=2, then at 10:01 we would trigger again? But then we are running two instances of the same job that were triggered at 10:00 and 10:01? That's overlapping.
Typically, with cron and max_concurrent>1, we allow multiple runs to be triggered at their scheduled times even if previous ones are running. So at 10:00 we trigger run1, at 10:01 we trigger run2, and they run concurrently.
So we want to create one run per scheduled time, regardless of how many are already running? But then we might have more than max_concurrent running? Because we are triggering at every scheduled time and not checking the current running count? But we are checking in the scheduler: we only create a run if current_running < max_concurrent. So if max_concurrent=2, and we have 2 running, then at the next scheduled time we won't create a run? That means we skip that scheduled time.
But then we are not running at fixed times if the job is always taking longer than the interval and we are at max_concurrent.
This is a trade-off. We are prioritizing not exceeding max_concurrent over running at every scheduled time.
So the design:
We trigger at every scheduled time, but only if we haven't reached max_concurrent. If we have, we skip that scheduled time and move to the next.
This means that if the job is consistently taking longer than the interval, we will eventually be always at max_concurrent and then we will skip all subsequent runs until one finishes? Then we will run at the next scheduled time after one finishes? But we are updating next_run even when we skip, so we are moving forward and not trying to run the skipped times.
Example:
Job: interval 1 minute, max_concurrent=1.
Run1 at 10:00 takes 2 minutes.
At 10:01: we skip because current_running=1, set next_run=10:02.
At 10:02: run1 is still running? Then skip, set next_run=10:03.
At 10:03: run1 finishes? Then at 10:03:05 (scheduler runs) we see next_run=10:03 (which is in the past) and current_running=0 -> create run2 for 10:03? But we skipped 10:01 and 10:02.
So we are running at 10:03, which is 3 minutes after the first run, even though the interval is 1 minute.
This might be acceptable because we don't want overlapping.
But what if the job fails and we retry? Then we have a pending run. The pending run is not running, so current_running=0. Then at the next scheduled time, we will create a new run? But we already have a pending run (the retry). So we will have two pending runs? Then when the retry runs, it will finish and then the next scheduled run will run? But we are allowing multiple pending? That's okay.
However, we might want to limit the number of pending runs? We don't want an infinite backlog of scheduled runs that haven't run because of concurrency? But we are skipping scheduled times when we are at max_concurrent, so we are not creating pending runs for those skipped times. We are only creating one run per scheduled time (if we can).
But what about retries? They are created when a run fails, and they are scheduled to run after retry_delay. They are independent of the scheduler's next_run? Yes, the retry is a new run with a scheduled_at in the future (now + retry_delay). But note: the retry run is not triggered by the scheduler? How do we run retries?
We have two ways to create runs:
1. The scheduler creates runs for the scheduled times.
2. When a run fails, we create a retry run (with status pending and scheduled_at = now + retry_delay).
But then the retry run is not tied to the job's next_run? So we might have two runs for the same job at the same time: one from the scheduler and one retry? That's possible.
We need to decide: are retries subject to the same concurrency limits? Yes, because they are runs of the same job.
So when we create a retry, we should check concurrency? But the retry is created by the worker after a failure. At that moment, the current_running might be 0 (because the run that failed is no longer running). But we are about to create a pending run. Then when the scheduler runs, it will see current_running=0 and create a new run for the scheduled time? Then we have two pending runs? That's acceptable.
But if the retry is scheduled to run at a time when the scheduler also wants to run, then we might have two runs scheduled at the same time? The scheduler runs every minute and creates runs for the scheduled time. The retry is scheduled for a specific time (now+retry_delay). They might coincide.
We can handle retries by having a separate mechanism: the worker, when it fails, creates a new run with status pending and scheduled_at = now + retry_delay. Then we don't go through the scheduler? But then we need to dispatch that run. We can have a single queue for all pending runs (both from scheduler and retries) that are due (scheduled_at <= now). Then the dispatcher picks from that queue.
Alternatively, we can have the scheduler also pick up retries? But the retries have their own scheduled time.
Let's change the design:
We have a table `job_runs` with:
run_id, job_id, status, scheduled_at, started_at, finished_at, retry_count, next_retry_at, etc.
We have a dispatcher that periodically (every second) checks for runs that are pending and scheduled_at <= now, and then tries to dispatch them (if concurrency allows).
The scheduler only creates new runs for the scheduled times and updates the job's next_run.
The dispatcher:
For each run with status='pending' and scheduled_at <= now:
Check the job's current running runs (status='running') count.
If count < job.max_concurrent, then set the run's status to 'running' and assign a worker.
But then we have two components that create runs? The scheduler creates runs for the schedule, and the worker (on failure) creates retry runs? Actually, the worker, when it fails, updates the run's retry_count and if we should retry, it sets the run's status back to 'pending' and updates scheduled_at to now + retry_delay? Or we create a new run? We can update the existing run.
Let's decide:
When a run fails:
If retry_count < max_retries:
retry_count += 1
scheduled_at = NOW() + retry_delay
status = 'pending'
Else:
status = 'failed'
Then the dispatcher will pick it up when scheduled_at <= now.
But then we are reusing the same run_id for retries? That's acceptable.
Then the scheduler only creates new runs for the job's schedule. And the dispatcher picks up both scheduled runs and retries.
Now, the concurrency check in the dispatcher: we check the current running runs for the job. But note: the run that failed is no longer running (status is set to 'pending' again). So we are counting only runs with status='running'.
But what about the run that we are about to dispatch? We are about to set it to 'running'. So we check: current_running (excluding this run) < max_concurrent? Then we set it to running.
However, we might have multiple dispatchers? We need to lock the job when we check and update? Or we can use a lock on the run? We are updating the run's status from pending to running. We can do:
UPDATE job_runs
SET status = 'running', started_at = NOW()
WHERE run_id = ? AND status = 'pending' AND scheduled_at <= NOW();
Then check the number of rows updated? But we also need to check concurrency? We can do:
In a transaction:
SELECT COUNT(*) FROM job_runs WHERE job_id = ? AND status='running' FOR UPDATE? That would lock all running runs for the job? That might be heavy.
Alternatively, we can use a lock on the job row? But then we are serializing all dispatches for the same job? That might be acceptable.
Let's have a job_locks table? Or we can use the job row lock.
We'll do:
Dispatcher:
Find a pending run (scheduled_at <= now) for a job that has available concurrency.
How to do that efficiently?
We can have a queue of pending runs ordered by scheduled_at. Then for each pending run, we check the job's current running count. But we need to avoid race conditions.
We can do:
BEGIN;
SELECT run_id FROM job_runs
WHERE status='pending' AND scheduled_at <= NOW()
ORDER BY scheduled_at
LIMIT 1
FOR UPDATE SKIP LOCKED? But we are not locking the runs? We want to lock the job when we check concurrency.
Alternatively, we can lock the job row when we check concurrency and then update the run.
Steps for dispatcher:
Find a pending run (with scheduled_at <= now) that we can run.
We can do:
SELECT run_id, job_id
FROM job_runs
WHERE status='pending' AND scheduled_at <= NOW()
ORDER BY scheduled_at
LIMIT 1;
Then for that run, get the job and lock the job row (SELECT * FROM jobs WHERE job_id = ? FOR UPDATE). Then check the current running count for that job. If we can run, then update the run to running.
But what if two dispatchers pick the same run? We are not locking the run row when we select. We can use SKIP LOCKED on the run? But we want to lock the job, not the run.
Alternatively, we can have a separate table for job_locks? Or use advisory locks.
Given the complexity, we might assume that the dispatcher is a single process? But we want it to be distributed.
Let's assume we have multiple dispatchers. We need to avoid two dispatchers picking the same run and also avoid two dispatchers thinking they can run the same job (when max_concurrent=1).
We can do:
Step 1: Find a pending run that is due and lock the run row (SELECT ... FOR UPDATE). Then we have the run and we can update it to running without worrying about another dispatcher taking the same run.
Step 2: Then we check the job's current running count (excluding this run, because we are about to set it to running). But note: the run is currently pending, so it's not counted. We need to count the other running runs.
But what if between locking the run and checking the job's running count, another dispatcher has started another run for the same job? We need to lock the job row when checking the running count.
So:
BEGIN;
SELECT * FROM job_runs WHERE run_id = ? FOR UPDATE; -- lock the run
SELECT job_id FROM job_runs WHERE run_id = ?; -- get the job_id
SELECT * FROM jobs WHERE job_id = ? FOR UPDATE; -- lock the job
SELECT COUNT(*) FROM job_runs WHERE job_id = ? AND status='running' AND run_id != ?; -- count other running runs
IF count < job.max_concurrent THEN
UPDATE job_runs SET status='running', started_at=NOW() WHERE run_id = ?;
COMMIT;
dispatch to worker.
ELSE
ROLLBACK; -- we don't run this run now, but we leave it pending. Another dispatcher might try later.
END IF;
But then we are holding locks for a while? We are locking the job and the run. This might be acceptable if we have few jobs and dispatchers.
However, we might want to avoid locking the job for every pending run? We can try to find a run that we can run without locking the job first? But then we might have to retry.
Given the complexity, let's assume we have a single dispatcher? But then we don't have concurrency in dispatching? We can have multiple dispatchers but we use a distributed lock per job? We can use a lock service (like Redis) to lock the job when we check and update.
But to keep it simple, we'll assume a single dispatcher process.
Now, the worker:
The worker picks up a run that is in 'running' status? Actually, the dispatcher sets the run to 'running' and then assigns it to a worker (by putting it in a worker queue? or by calling the worker directly). We can have a queue (like RabbitMQ) for running jobs? But then we are just moving the run from pending to running and then to the worker queue.
Alternatively, the dispatcher can directly call the worker (or submit to a thread pool). But then we need to handle worker failures? We can have the worker update the run status when it finishes.
Let's have:
Dispatcher: when it decides to run a run, it sets status='running' and then submits the job to a worker pool (or a queue). The worker then executes the command and updates the run status to 'success' or 'failed'.
But what if the worker fails to update? We can have the dispatcher set a timeout? Or we can have the worker update the run status and if it doesn't, we have a reaper that checks for runs that have been running for too long and marks them as failed? That's another component.
Given the time, let's assume the worker updates the run status reliably.
Worker:
Execute the command.
If success: update run status to 'success', set finished_at.
If failure:
if run.retry_count < job.max_retries:
run.retry_count += 1
run.scheduled_at = NOW() + job.retry_delay
run.status = 'pending'
update run.
else:
run.status = 'failed'
update run.
But note: the run already has a retry_count? We are storing retry_count in the run.
Also, the job has max_retries and retry_delay. We can store these in the job and use them for retries.
However, what if the job definition changes (max_retries) after the run was created? We might want to use the job's current settings? Or the run's settings? We can store the retry policy in the run at creation time? But then if we change the job's retry policy, old runs use the old policy? That might be acceptable.
We'll store in the run: retry_count, and we use the job's current max_retries and retry_delay when retrying? But if the job's max_retries is changed, then a run that has already retried 2 times (with old max_retries=3) and now the job's max_retries=1, then we should not retry again? We should use the job's current max_retries? Or the run's? Let's use the job's current max_retries? But then if we increase max_retries, old runs that have failed can retry more? That might be desirable.
We'll use the job's current max_retries and retry_delay at the time of retry.
So in the worker, when we fail, we look up the job (by job_id) and get the current max_retries and retry_delay.
Now, what about the dispatcher? It uses the job's current max_concurrent.
So the job definition can change and affect new runs and retries.
This is acceptable.
Let's summarize the tables:
Table jobs:
job_id (PK)
command
schedule_type ('cron', 'interval', 'one-time')
schedule_value (cron string, interval seconds, or timestamp for one-time)
max_concurrent (default 1)
max_retries (default 0)
retry_delay (default 0, in seconds)
next_run (timestamp, the next scheduled time for the scheduler to trigger)
created_at
updated_at
Table job_runs:
run_id (PK)
job_id (FK to jobs)
status ('pending', 'running', 'success', 'failed')
scheduled_at (the intended time of this run, for scheduled runs from the scheduler, or the retry time for retries)
started_at (when the run actually started)
finished_at (when the run finished)
retry_count (for this run, how many times we have retried? Actually, we are reusing the same run for retries, so this is the total number of attempts? We can call it attempt_count)
created_at
updated_at
The scheduler:
Runs every minute (or more frequently).
For each job where next_run <= now:
Lock the job row.
Check current running runs (status='running') for the job.
If current_running < max_concurrent:
Create a new run with status='pending', scheduled_at = next_run, attempt_count=0.
Then update next_run to the next scheduled time after the current next_run (using the job's schedule). If the job is one-time, set next_run to null.
The dispatcher (single process, or distributed with job locking):
Periodically (every second) checks for pending runs with scheduled_at <= now.
For each such run (in order of scheduled_at):
Lock the run row and the job row.
Check current running runs for the job (excluding this run? but the run is pending, so it's not running). If current_running < job.max_concurrent:
Set the run status to 'running', started_at = now.
Then dispatch to a worker (or put in a worker queue).
Else:
Leave the run pending and try the next one.
The worker:
Execute the command.
On success: set status='success', finished_at=now.
On failure:
Look up the job (by job_id) to get current max_retries and retry_delay.
If run.attempt_count < job.max_retries:
run.attempt_count += 1
run.scheduled_at = NOW() + job.retry_delay
run.status = 'pending'
update run.
Else:
run.status = 'failed'
update run.
Note: when we retry, we set the run to pending and scheduled_at in the future. Then the dispatcher will pick it up when scheduled_at <= now.
But what if the retry_delay is 0? Then we retry immediately. Then the dispatcher will pick it up immediately (if concurrency allows).
This design has:
- Schedules: handled by the scheduler and the job's next_run.
- Dedup: we only create one run per scheduled time (because we update next_run after creating a run). But note: if the scheduler runs multiple times in the same minute, it will only create one run because the job row is locked and next_run is updated.
- Concurrency caps: the dispatcher checks the current running count before setting a run to running.
- Retries: handled by the worker on failure.
However, there is a race condition:
Two dispatchers might pick the same pending run? We lock the run row when we select it? We can use SELECT ... FOR UPDATE SKIP LOCKED to avoid two dispatchers picking the same run.
But we also lock the job row when we check concurrency? That might be heavy.
Alternatively, we can have a separate table for job_locks? Or use advisory locks.
Given the complexity of distributed systems, we might assume that the dispatcher is a single process. Then we don't have to worry about multiple dispatchers.
But if we want multiple dispatchers, we need to use a lock on the job when we check concurrency and update the run. We can use a database row lock on the job, but that might be a bottleneck.
We can try to optimize by:
- Having a cache of current running counts per job? But then we have to update the cache when runs start and finish, and that's error-prone.
Given the time, we'll leave it as a single dispatcher.
Now, what about the scheduler? We can have multiple schedulers? We use the job row lock, so only one scheduler will update the job at a time.
So the design works with multiple schedulers and a single dispatcher? Or multiple dispatchers with job locking? We'll leave the dispatcher as a single process for now.
But note: the dispatcher and scheduler are separate. The scheduler creates pending runs, and the dispatcher moves them to running.
We can combine them? But they have different frequencies: scheduler runs every minute, dispatcher every second.
We'll keep them separate.
Now, let's write some pseudo-code for the scheduler and dispatcher.
Scheduler (runs every minute, or more frequently for interval jobs):
SELECT job_id, next_run, schedule_type, schedule_value, max_concurrent
FROM jobs
WHERE next_run <= NOW() AND enabled = true;
For each job:
BEGIN;
SELECT * FROM jobs WHERE job_id = ? FOR UPDATE;
-- Double check next_run because it might have been updated by another scheduler?
IF job.next_run > NOW() THEN
COMMIT;
CONTINUE;
END IF;
-- Calculate the intended scheduled time for this run: it's job.next_run.
intended_scheduled_time = job.next_run;
-- Count current running runs for this job
running_count = SELECT COUNT(*) FROM job_runs
WHERE job_id = job.job_id AND status='running';
IF running_count < job.max_concurrent THEN
-- Create a new run
INSERT INTO job_runs (job_id, status, scheduled_at, created_at)
VALUES (job.job_id, 'pending', intended_scheduled_time, NOW());
END IF;
-- Update next_run for the job to the next scheduled time after intended_scheduled_time.
next_run = calculate_next_run(job.schedule_type, job.schedule_value, intended_scheduled_time);
UPDATE jobs SET next_run = next_run WHERE job_id = job.job_id;
COMMIT;
Dispatcher (runs every second):
SELECT run_id, job_id
FROM job_runs
WHERE status='pending' AND scheduled_at <= NOW()
ORDER BY scheduled_at
LIMIT 1;
IF found:
BEGIN;
SELECT * FROM job_runs WHERE run_id = ? FOR UPDATE;
SELECT * FROM jobs WHERE job_id = ? FOR UPDATE;
-- Check again if the run is still pending and scheduled_at <= NOW()? It might have been updated by another dispatcher? But we locked the run.
-- Count current running runs for the job (excluding this run? but this run is pending, so we don't exclude)
running_count = SELECT COUNT(*) FROM job_runs
WHERE job_id = job.job_id AND status='running';
IF run.status = 'pending' AND run.scheduled_at <= NOW() AND running_count < job.max_concurrent THEN
UPDATE job_runs
SET status='running', started_at=NOW()
WHERE run_id = run.run_id;
COMMIT;
-- Dispatch to worker (asynchronously)
dispatch_to_worker(run.run_id);
ELSE
COMMIT;
-- Try the next pending run? We are only picking one at a time. We can loop until we can't dispatch any more? But we are in a loop that runs every second? We can try to dispatch as many as possible in one go? But then we might hold locks for too long.
-- Alternatively, we can try to dispatch one run per dispatcher iteration and then let the next iteration pick the next.
END IF;
END IF;
Worker:
function run_job(run_id):
run = SELECT * FROM job_runs WHERE run_id = run_id;
job = SELECT * FROM jobs WHERE job_id = run.job_id;
try:
execute(job.command)
UPDATE job_runs
SET status='success', finished_at=NOW()
WHERE run_id = run_id;
catch (error):
-- Get current job settings (in case they changed)
job = SELECT * FROM jobs WHERE job_id = run.job_id;
IF run.retry_count < job.max_retries:
UPDATE job_runs
SET retry_count = retry_count + 1,
scheduled_at = NOW() + INTERVAL job.retry_delay SECOND,
status = 'pending'
WHERE run_id = run_id;
ELSE:
UPDATE job_runs
SET status='failed', finished_at=NOW()
WHERE run_id = run_id;
This design should work for a single dispatcher and multiple workers.
However, we have not addressed:
- What if the dispatcher fails after setting a run to 'running' but before dispatching to worker? Then the run is stuck in 'running'. We need a reaper that marks runs that have been running for too long as failed? Or we can have the worker update the run status and if the worker never runs, then the run remains running? We can have a timeout for runs.
We can add:
In the job_runs table, we can have a 'timeout' column? Or we can have a reaper that checks for runs that have been running for more than a certain threshold (maybe the job's expected runtime?) and mark them as failed.
But we don't have an expected runtime in the job definition. We can add a `timeout` column in the job? Or we can have a global timeout? Or we can have the worker update a heartbeat? This is getting complex.
Given the time, we'll assume that the worker always updates the run status and doesn't crash. But in reality, we need to handle worker crashes.
We can have the dispatcher set a timeout when it sets the run to running? And then if the run doesn't finish within the timeout, the reaper marks it as failed and then we can retry? But then we might have two workers running the same job? Because the worker that was assigned might still be running? We need to make the job idempotent or have a way to stop the worker.
This is a hard problem. We'll leave it for now.
Another issue: what if the dispatcher and scheduler are in different time zones? We should use UTC everywhere.
Let's note that.
We'll also need a way to manually trigger a job? That can be done by inserting a run directly with status='pending' and scheduled_at=NOW().
And a way to cancel a job? We can delete the job and its runs? Or mark the job as disabled.
We'll add an `enabled` flag in the jobs table.
Now, let's write the function to calculate next_run.
For cron: we need a function that given a cron expression and a datetime, returns the next datetime that matches the cron.
For interval: next_run = last_scheduled_time + interval_seconds.
For one-time: next_run = NULL after the first run.
We can implement these in the application code.
This design is a good starting point.
However, we have not addressed:
- Job dependencies: one job might depend on another? That's out of scope.
- Resource constraints: we might want to limit the total number of concurrent runs across all jobs? We can have a global concurrency limit? We can check the total running runs (across all jobs) against a global limit? That would require a global lock? We can do that in the dispatcher: check total running runs (across all jobs) and if we are below the global limit, then we can run. But then we need to know the global limit? We can set a global max_concurrent? Or per resource? This is getting too complex.
We'll stick to per-job concurrency.
Finally, we need to store the job definitions and runs in a persistent store. We'll use a SQL database.
Let's create the tables:
CREATE TABLE jobs (
job_id UUID PRIMARY KEY,
command TEXT NOT NULL,
schedule_type VARCHAR(20) NOT NULL, -- 'cron', 'interval', 'one-time'
schedule_value TEXT NOT NULL, -- cron string, interval seconds, or timestamp for one-time
max_concurrent INTEGER DEFAULT 1,
max_retries INTEGER DEFAULT 0,
retry_delay INTEGER DEFAULT 0, -- in seconds
next_run TIMESTAMP,
enabled BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE job_runs (
run_id UUID PRIMARY KEY,
job_id UUID REFERENCES jobs(job_id),
status VARCHAR(20) NOT NULL, -- 'pending', 'running', 'success', 'failed'
scheduled_at TIMESTAMP NOT NULL,
started_at TIMESTAMP,
finished_at TIMESTAMP,
retry_count INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
We'll also need indexes:
CREATE INDEX idx_job_runs_job_id_status ON job_runs(job_id, status);
CREATE INDEX idx_job_runs_scheduled_at ON job_runs(scheduled_at) WHERE status='pending';
CREATE INDEX idx_jobs_next_run ON jobs(next_run) WHERE enabled=true;
This is a basic design. There are many edge cases and optimizations to consider.
Given the complexity of distributed systems, we might want to use an existing solution like Temporal, Airflow, or similar. But if we are building from scratch, this is a starting point.
Let me know if you have any questions or need more details.</think>