83 lines
2.0 KiB
JavaScript
83 lines
2.0 KiB
JavaScript
// Logging
|
|
const log = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.js.utils.TimerMgr');
|
|
|
|
class TimerMgr {
|
|
|
|
#timers = new Object();
|
|
|
|
constructor() {
|
|
log.info('Initialization of TimerMgr helper class');
|
|
}
|
|
|
|
create(id, timeout, func, ...params) {
|
|
if (this.hasTimer(id)) {
|
|
this.cancel(id);
|
|
}
|
|
log.debug("Create timer with id " + id);
|
|
this.#timers[id] = actions.ScriptExecution.createTimer(id, timeout, func, ...params);
|
|
}
|
|
|
|
cancel(id) {
|
|
// Return if no timer with the respactive id is available
|
|
if (!this.hasTimer(id)) {
|
|
log.warn(`No timer with id ${id} available to cancel`);
|
|
return false;
|
|
}
|
|
|
|
// Check if timer is active
|
|
if (!this.#timers[id].isActive()) {
|
|
log.debug(`Timer with id ${id} not running. Cancel anyway`);
|
|
} else {
|
|
log.debug(`Cancel timer with identifier ${id}`);
|
|
}
|
|
|
|
// Cancel timer
|
|
this.#timers[id].cancel();
|
|
delete this.#timers[id];
|
|
}
|
|
|
|
hasTimer(id) {
|
|
return this.#timers.hasOwnProperty(id);
|
|
}
|
|
|
|
isActive(id) {
|
|
if (!this.hasTimer(id)) {
|
|
log.warn(`No timer with id ${id} found`);
|
|
return false;
|
|
}
|
|
return this.#timers[id].isActive();
|
|
}
|
|
|
|
cancelAll() {
|
|
// Fetch timers
|
|
let timers = Object.keys(this.#timers);
|
|
|
|
// Return if no timers available
|
|
if (timers.length == 0) {
|
|
log.debug('No timers available to cancel');
|
|
return false;
|
|
}
|
|
|
|
// Cancel all timers
|
|
for (let timer of timers) {
|
|
this.cancel(timer);
|
|
}
|
|
}
|
|
|
|
reschedule(id, timeout) {
|
|
if (!this.hasTimer(id)) {
|
|
log.warn(`Cannot reschedule non-existent timer with id ${id}`);
|
|
return false;
|
|
}
|
|
this.#timers[id].reschedule(timeout);
|
|
}
|
|
}
|
|
|
|
function getTimerMgr () {
|
|
return new TimerMgr();
|
|
}
|
|
|
|
module.exports = {
|
|
TimerMgr,
|
|
getTimerMgr
|
|
}; |