generated from your-land/yl_template
87 lines
2.8 KiB
Lua
87 lines
2.8 KiB
Lua
local function calculate_bucket(bucket, data) -- This is per bucket
|
|
|
|
if type(bucket) ~= "number" then bucket = tonumber(bucket) end
|
|
|
|
local affected_tickers = {}
|
|
|
|
for _, ticker in pairs(data) do
|
|
if ticker.frequency == bucket then
|
|
table.insert(affected_tickers, ticker)
|
|
end
|
|
end
|
|
|
|
-- Prevent division by 0
|
|
if (#affected_tickers == 0) then
|
|
-- If the bucket has no affected members, then there is nothing to recalculate
|
|
minetest.log("warn",
|
|
"[yl_ticker] globalstep division by zero, no members of bucket = " ..
|
|
dump(bucket))
|
|
return
|
|
end
|
|
|
|
-- Let's calculate the distance
|
|
local distance = bucket / #affected_tickers
|
|
|
|
local n = 0
|
|
for _, ticker in ipairs(affected_tickers) do
|
|
ticker._next_runtime = os.time() + n * distance
|
|
n = n + 1
|
|
end
|
|
end
|
|
|
|
local delta = 1
|
|
local timer = 0
|
|
|
|
local gs = function(dtime)
|
|
timer = timer + dtime
|
|
if timer <= delta then return end
|
|
timer = timer - delta
|
|
|
|
-- payload
|
|
local success, data = yl_ticker.list()
|
|
if ((success == false) or (data == nil)) then
|
|
return false, "Could not retrieve list"
|
|
end
|
|
|
|
local current_time = os.time()
|
|
local changed_buckets = {}
|
|
|
|
-- Check if any ticker should be displayed
|
|
for _, ticker in pairs(data) do
|
|
if current_time >= (ticker._next_runtime or 0) then
|
|
if (type(ticker._next_runtime) ~= "number") then
|
|
table.insert(changed_buckets, ticker.frequency)
|
|
else
|
|
yl_ticker.log(os.date("!%H:%M:%S", os.time()) .. " = " ..
|
|
tostring(ticker.id))
|
|
local a_success, message = yl_ticker.say(ticker.id, "*")
|
|
if (a_success == false) then
|
|
minetest.log("error",
|
|
"[yl_ticker] globalstep cannot send to target, message = " ..
|
|
dump(message) .. " : ticker = " ..
|
|
dump(ticker))
|
|
end
|
|
ticker._next_runtime = ticker._next_runtime +
|
|
(ticker.frequency or
|
|
yl_ticker.settings.frequency)
|
|
end
|
|
end
|
|
|
|
-- Check if this ticker needs to be removed from the list due to runtime expired.
|
|
if ((type(ticker.runtime) == "number") and
|
|
(current_time > ticker.runtime)) then
|
|
yl_ticker.delete(ticker.id)
|
|
table.insert(changed_buckets, ticker.frequency)
|
|
end
|
|
end
|
|
|
|
-- If there were any tickers that had no _next_runtime, then we need to recalculate their bucket
|
|
if next(data) then
|
|
for _, bucket in ipairs(changed_buckets) do
|
|
calculate_bucket(bucket, data)
|
|
end
|
|
end
|
|
end
|
|
|
|
minetest.register_globalstep(gs)
|