Software / code / prosody
Comparison
plugins/mod_cron.lua @ 13284:ffd3dadf6247
mod_cron: Make task frequencies configurable in overly generic manner
Requested feature for many modules, notably MAM and file sharing.
| author | Kim Alvefur <zash@zash.se> |
|---|---|
| date | Sun, 22 Oct 2023 18:58:02 +0200 |
| parent | 13269:d50bee584969 |
| child | 13364:6f9b15757384 |
comparison
equal
deleted
inserted
replaced
| 13283:1c63b8c3cd9d | 13284:ffd3dadf6247 |
|---|---|
| 1 module:set_global(); | 1 module:set_global(); |
| 2 | 2 |
| 3 local async = require("prosody.util.async"); | 3 local async = require("prosody.util.async"); |
| 4 | |
| 5 local periods = { hourly = 3600; daily = 86400; weekly = 7 * 86400 } | |
| 6 | 4 |
| 7 local active_hosts = {} | 5 local active_hosts = {} |
| 8 | 6 |
| 9 function module.add_host(host_module) | 7 function module.add_host(host_module) |
| 10 | 8 |
| 27 task.name = task.when; | 25 task.name = task.when; |
| 28 end | 26 end |
| 29 if task.id == nil then | 27 if task.id == nil then |
| 30 task.id = event.source.name .. "/" .. task.name:gsub("%W", "_"):lower(); | 28 task.id = event.source.name .. "/" .. task.name:gsub("%W", "_"):lower(); |
| 31 end | 29 end |
| 30 task.period = host_module:get_option_period(task.id:gsub("/", "_") .. "_period", "1" .. task.when, 60, 86400 * 7 * 53); | |
| 32 task.restore = restore_task; | 31 task.restore = restore_task; |
| 33 task.save = save_task; | 32 task.save = save_task; |
| 34 module:log("debug", "%s task %s added", task.when, task.id); | 33 module:log("debug", "%s task %s added", task.when, task.id); |
| 35 return true | 34 return true |
| 36 end | 35 end |
| 46 function host_module.unload() | 45 function host_module.unload() |
| 47 active_hosts[host_module.host] = nil; | 46 active_hosts[host_module.host] = nil; |
| 48 end | 47 end |
| 49 end | 48 end |
| 50 | 49 |
| 51 local function should_run(when, last) | 50 local function should_run(task, last) |
| 52 return not last or last + periods[when] * 0.995 <= os.time() | 51 return not last or last + task.period * 0.995 <= os.time() |
| 53 end | 52 end |
| 54 | 53 |
| 55 local function run_task(task) | 54 local function run_task(task) |
| 56 task:restore(); | 55 task:restore(); |
| 57 if not should_run(task.when, task.last) then | 56 if not should_run(task, task.last) then |
| 58 return | 57 return |
| 59 end | 58 end |
| 60 local started_at = os.time(); | 59 local started_at = os.time(); |
| 61 task:run(started_at); | 60 task:run(started_at); |
| 62 task.last = started_at; | 61 task.last = started_at; |