mirror of
https://git.minetest.land/MineClone2/MineClone2.git
synced 2025-01-01 14:17:29 +01:00
Add code to support cancelling jobs
This commit is contained in:
parent
06b8fa561e
commit
8dac0a34ef
@ -220,20 +220,34 @@ local function queue_task(when, priority, task)
|
|||||||
end
|
end
|
||||||
vl_scheduler.queue_task = queue_task
|
vl_scheduler.queue_task = queue_task
|
||||||
|
|
||||||
|
local task_metatable = {
|
||||||
|
__index = {
|
||||||
|
cancel = function(self)
|
||||||
|
self.real_func = function() end
|
||||||
|
end,
|
||||||
|
func = function(self)
|
||||||
|
self.real_func(unpack(self.args))
|
||||||
|
end,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
local function vl_scheduler_after(time, priority, func, ...)
|
local function vl_scheduler_after(time, priority, func, ...)
|
||||||
local task = new_task()
|
local task = new_task()
|
||||||
task.args = {...}
|
task.args = {...}
|
||||||
task.next = nil
|
task.next = nil
|
||||||
task.real_func = func
|
task.real_func = func
|
||||||
task.func = function(task) task.real_func(unpack(task.args)) end
|
setmetatable(task, task_metatable)
|
||||||
local timesteps = math.round(time / 0.05)
|
local timesteps = math.round(time / 0.05)
|
||||||
queue_task(timesteps, priority, task)
|
queue_task(timesteps, priority, task)
|
||||||
|
|
||||||
|
-- Return a job handle that can cancel
|
||||||
|
return task
|
||||||
end
|
end
|
||||||
vl_scheduler.after = vl_scheduler_after
|
vl_scheduler.after = vl_scheduler_after
|
||||||
|
|
||||||
-- Hijack core.after and redirect to this scheduler
|
-- Hijack core.after and redirect to this scheduler
|
||||||
function core.after(time, func, ...)
|
function core.after(time, func, ...)
|
||||||
vl_scheduler_after(time, 2, func, ...)
|
return vl_scheduler_after(time, 2, func, ...)
|
||||||
end
|
end
|
||||||
|
|
||||||
return vl_scheduler
|
return vl_scheduler
|
||||||
|
@ -201,5 +201,18 @@ describe('vl_scheduler',function()
|
|||||||
call_globalstep(0.05)
|
call_globalstep(0.05)
|
||||||
end)
|
end)
|
||||||
end)
|
end)
|
||||||
|
it('can provide cancellable jobs from core.after()',function()
|
||||||
|
local after = _G.core.after
|
||||||
|
local ran = false
|
||||||
|
local job = after(1,function()
|
||||||
|
ran = true
|
||||||
|
end)
|
||||||
|
call_globalstep(0.5)
|
||||||
|
assert.no_error(function()
|
||||||
|
job:cancel()
|
||||||
|
end)
|
||||||
|
for i = 1,10 do call_globalstep(0.5) end
|
||||||
|
assert.is_false(ran)
|
||||||
|
end)
|
||||||
end)
|
end)
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user