Requirements of a task scheduler
medium 26 minA task scheduler runs work later, in the right order, on many machines, and does not forget it.
Requirements as a small scheduler with rules
Read it, run it, change a line and run it again.
Loading editor…
It runs in memory with a clock that we move by hand. Each rule of the page is a few lines: validate, key, store, priority with aging, dependencies, lease, retries, dead letter, cancel, pause.
The same in TypeScript
// The parts of the contract, as types, with priority queue and retry delay.type Priority = "critical" | "high" | "medium" | "low";type Status = "pending" | "scheduled" | "running" | "completed" | "failed" | "cancelled";interface RetryPolicy { maxRetries: number; backoff: "linear" | "exponential"; initialMs: number; maxMs: number }interface Task { id: string; name: string; payload: Record<string, unknown>; scheduledAt: Date; priority: Priority; retry: RetryPolicy; timeoutMs: number; dependencies: string[]; status: Status;}interface SchedulerApi { submitTask(task: Omit<Task, "id" | "status">, idempotencyKey: string): Promise<string>; scheduleRecurring(task: Omit<Task, "id" | "status">, cron: string): Promise<string>; getTaskStatus(id: string): Promise<Status>; cancelTask(id: string): Promise<boolean>; listTasks(filter: Partial<Pick<Task, "status" | "priority">>): Promise<Task[]>;}const TARGETS = { availability: 0.9999, submitP50Ms: 50, submitP99Ms: 200, startP99Ms: 5000 };class PriorityTaskQueue { private queues = new Map<Priority, Task[]>([["critical", []], ["high", []], ["medium", []], ["low", []]]); enqueue(t: Task) { this.queues.get(t.priority)!.push(t); } dequeue(): Task | undefined { // strict: a real one needs aging for (const q of this.queues.values()) if (q.length) return q.shift(); return undefined; }}function retryDelay(p: RetryPolicy, attempt: number): number { const raw = p.backoff === "exponential" ? p.initialMs * 2 ** attempt : p.initialMs * (attempt + 1); return Math.random() * Math.min(raw, p.maxMs); // cap both kinds, then jitter}The same in Java
// The same contract in Java.enum Priority { CRITICAL, HIGH, MEDIUM, LOW }enum Status { PENDING, SCHEDULED, RUNNING, COMPLETED, FAILED, CANCELLED }enum Backoff { LINEAR, EXPONENTIAL }record RetryPolicy(int maxRetries, Backoff backoff, long initialMs, long maxMs) { long delay(int attempt) { long raw = backoff == Backoff.EXPONENTIAL ? initialMs * (1L << Math.min(attempt, 30)) : initialMs * (attempt + 1L); return ThreadLocalRandom.current().nextLong(Math.min(raw, maxMs) + 1); }}record Task(String id, String name, Map<String, Object> payload, Instant scheduledAt, Priority priority, RetryPolicy retry, long timeoutMs, List<String> dependencies, Status status) {}final class PriorityTaskQueue { private final Map<Priority, Queue<Task>> queues = new EnumMap<>(Priority.class); PriorityTaskQueue() { for (Priority p : Priority.values()) queues.put(p, new ConcurrentLinkedQueue<>()); } void enqueue(Task t) { queues.get(t.priority()).offer(t); } Optional<Task> dequeue() { // strict: a real one needs aging for (Queue<Task> q : queues.values()) { // EnumMap keeps the order of the enum Task t = q.poll(); if (t != null) return Optional.of(t); } return Optional.empty(); }}