Files

58 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2026-10-29 11:57:29 +01:00
// Generated, do not edit. sha256:e2e2ad5112c13991dd020e8231ee0569ddfef89365ad659158d7e3d71cc43739
import { timerSetting } from '../app-settings.js';
import { CONFIG } from '../../shared/config.js';
import { pollChanges } from '../changes.js';
const TASKS = [
{
key: 'spot_refresh',
prefField: 'spot_refresh_seconds',
run: () => document.dispatchEvent(new CustomEvent('tick:spot')),
},
{
key: 'bus_poll',
prefField: 'bus_poll_seconds',
run: () => pollChanges(),
},
];
const handles = new Map();
function intervalSecondsFor(task) {
const s = timerSetting(task.prefField);
return Number.isInteger(s) ? s : CONFIG.TIMERS.OFF_SECONDS;
}
function stop(task) {
const h = handles.get(task.key);
if (h !== undefined) { clearTimeout(h); handles.delete(task.key); }
}
function start(task) {
stop(task);
if (intervalSecondsFor(task) >= CONFIG.TIMERS.OFF_SECONDS) return;
const tick = async () => {
if (document.visibilityState !== 'hidden') {
try { await task.run(); } catch (e) { console.error('[scheduler]', task.key, e); }
}
const next = intervalSecondsFor(task);
if (next >= CONFIG.TIMERS.OFF_SECONDS) { handles.delete(task.key); return; }
handles.set(task.key, setTimeout(tick, next * 1000));
};
const seconds = intervalSecondsFor(task);
handles.set(task.key, setTimeout(tick, seconds * 1000));
}
function startAll() { for (const task of TASKS) start(task); }
export function initScheduler() {
startAll();
document.addEventListener('settings-changed', startAll);
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') return;
for (const task of TASKS) {
if (!handles.has(task.key)) continue;
try { task.run(); } catch (e) { console.error('[scheduler]', task.key, e); }
}
});
}