Code: Select all
-- Copyright (C) AldoBr - WTFPL
-- Usefull routines for scheduling repetitive tasks
-- Scheduler object
function createscheduler()
return {
-- Number of ticks since game started
timerticks = 0,
-- Table containning the events
events = { },
-- Last Id used
lastschedulerentryid = -1,
-- Get a new ID for the event
createnewschedulerentryid = function(pThis)
lastschedulerentryid = lastschedulerentryid + 1
return lastschedulerentryid
end,
-- Scheduler entry object
-- pTime is the time that the event will take place first (in number of timer ticks since server started)
-- pRepeatTimes is the number of times the event should be repeated (-1 to repeat indefinitely)
-- pRepeatInterval is the interval in timer ticks between each repetition
-- pFunction is the function that should be called when the event takes place
createevent = function(pThis, pTime, pRepeatTimes, pRepeatInterval, pFunction)
local id = createnewschedulerentryid()
pThis.events[id] = {
eventtime = pTime,
eventrepeat = pRepeatTimes,
eventinterval = pRepeatInterval,
eventfunction = pFunction,
processevent = function(aThis)
if eventrepeat > 0 then -- repeat is a positive integer, number of repetitions
aThis:eventfunction()
aThis.eventrepeat = aThis.eventrepeat - 1
aThis.eventtime = aThis.eventtime + aThis.eventinterval
elseif eventrepeat < 0 then -- repeat is a negative integer, repeat indefinitely
aThis:eventfunction()
elseif eventrepeat = 0 then -- repeat reached 0, remove event
pThis.events[id] = nil
end
end
}
return id
end,
-- Deletes the event pointed to by pID
deleteevent = function(pThis, pID)
pThis.events[pID] = nil
end
-- Check events
checkevents = function(pThis)
for _, value in pairs(pThis.events) do
if pThis.timerticks >= value.eventtime then
value:processevent()
end
end
end
}
end
-- Timer tick ammount of seconds
defaultschedulertimerticks = 60 -- tick each minute
-- Creates a default scheduler
defaultscheduler = createscheduler()
-- Function to activate the default scheduler in a minetest.after event
defaultschedulerfunction = function()
defaultscheduler.timerticks = timerticks + 1
defaultscheduler:checkevents()
minetest.after(defaultschedulertimerticks, defaultschedulerfunction)
end
-- Setup the default scheduler
minetest.after(defaultschedulertimerticks, defaultschedulerfunction)
-- this will trigger a event five minutes later and keep repeating indefinitely each 5 minutes (-1 repeat means repeat indefinitely)
defaultscheduler:createevent(defaultscheduler.timerticks + 5, -1, 5, function print('5 minutes') end)
Code is untested. License is WTFPL.