Home/Low-level design/Task Scheduler

Task Scheduler

Priority dispatch, worker quotas, and expiring leases

Priority and lease validity are independent dimensions. A task can be pending, running with a specific lease, or permanently done. Expiry returns a running task to pending and reclaims worker capacity.

go
type Lease struct { Token,ExpiresAt int }
old, current := Lease{Token: 1}, Lease{Token: 2}
fmt.Println(old.Token == current.Token) // stale worker cannot complete current lease

A monotonically increasing token fences stale completion, even if the same worker receives the task again. Every valid timed call expires leases before answering, including unknown-worker requests. Invalid duration must not advance time or trigger expiry. Numeric task IDs break priority ties; lexicographic string IDs would misorder 10 and 2. Logical timestamps avoid sleeps and make the exact expiry boundary testable.

Go models this service with a struct and pointer-receiver methods. Constructor functions return a pointer; validation failures return errors rather than panicking. Scalars in snapshot structs are copied by value. Maps, slices, and optional pointers still require detached copies when crossing the service boundary. Go maps do not have key iteration order; use ordered slices for ranked results. There are no threads, persistence, wall-clock reads, or external side effects in this exercise.

Put it into practice

Implement the exercise in a full-screen workspace, then run its tests.

Open practice
Next lessonRecipe Manager