Lua Project: Task Scheduler
A task scheduler is a program that runs several coroutines in priority order over simulated ticks. A tick is one step of simulated time advanced by the scheduler.
Priority sets the running order
Tasks are sorted by priority, highest first. The first task in the sorted list runs first.
local tasks = { { name = "low", priority = 1 }, { name = "high", priority = 9 } }
table.sort(tasks, function(a, b) return a.priority > b.priority end)
print(tasks[1].name .. ", " .. tasks[2].name)A task yields, then resumes
The first resume runs the task until it yields. The scheduler prints its tick, then resumes the task to finish.
local co = coroutine.create(function() coroutine.yield() print("resumed") end)
coroutine.resume(co)
print("scheduler tick")
coroutine.resume(co)A task yields a work request
The yielded value comes back from resume. The scheduler reads it as the task request.
local co = coroutine.create(function() coroutine.yield("work") end)
local ok, request = coroutine.resume(co)
print(request)Example
local function makeTask(steps)
return coroutine.create(function()
for i = 1, steps do coroutine.yield() end
end)
end
local tasks = {
{ name = "report", priority = 3, co = makeTask(1) },
{ name = "backup", priority = 2, co = makeTask(2) },
{ name = "clean", priority = 1, co = makeTask(1) }
}
table.sort(tasks, function(a, b) return a.priority > b.priority end)
local done = {}
local ticks = 0
for _, t in ipairs(tasks) do
while coroutine.status(t.co) ~= "dead" do
coroutine.resume(t.co)
ticks = ticks + 1
end
done[#done + 1] = t.name
end
print("done: " .. table.concat(done, ", "))
print("ticks: " .. ticks)Key points
- Task: each task is a coroutine that yields a work request.
- Priority: a higher priority number runs before a lower one.
- Tick: a tick is one step of simulated time advanced by the scheduler.
- Yield: a task yields when it waits, so the scheduler can run another task.
- Report: the scheduler prints completions in the order tasks finish.
In this example, three tasks are sorted by priority, highest first. The scheduler resumes each task until it finishes, counting one tick per resume. The report lists completions in priority order, with seven ticks in total.
Note
simulated ticks are counters, not real clock time.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Three tasks have priorities 1, 2, and 3. Which task runs first?