13842653a2f5d63cedfaec663526032bdc7d5e35
3 const { ChoreError
} = require('./errors');
4 const { fileScope
} = require('@squeep/log-helper');
5 const _fileScope
= fileScope(__filename
);
12 * @param {ConsoleLike} logger
19 _getChore(choreName
) {
20 const chore
= this.chores
[choreName
]; // eslint-disable-line security/detect-object-injection
22 throw new ChoreError('chore does not exist');
28 * Register a chore task to be called every intervalMs.
29 * Zero interval will only register task, will not schedule any calls.
30 * @param {String} choreName
31 * @param {() => Promise(void)} choreFn
32 * @param {Number} intervalMs
34 establishChore(choreName
, choreFn
, intervalMs
= 0) {
35 const _scope
= _fileScope('establishChore');
37 if (choreName
in this.chores
) {
38 this.logger
.error(_scope
, 'chore already exists', { choreName
});
39 throw new ChoreError('chore exists');
42 const managedChoreFn
= async () => this.runChore(choreName
);
43 this.chores
[choreName
] = { // eslint-disable-line security/detect-object-injection
47 timeoutObj: intervalMs
? setTimeout(managedChoreFn
, intervalMs
).unref() : undefined,
48 nextSchedule: intervalMs
? new Date(Date
.now() + intervalMs
) : undefined,
53 * Invoke a chore task off-schedule, with any arguments.
54 * Resets timer of any next scheduled call.
55 * @param {String} choreName
56 * @param {...any} choreArgs
57 * @returns {Promise<void>}
59 async
runChore(choreName
, ...choreArgs
) {
60 const _scope
= _fileScope('runChore');
62 const chore
= this._getChore(choreName
);
64 if (chore
.isRunning
) {
65 this.logger
.debug(_scope
, 'chore already running, skipping', { choreName
});
69 chore
.isRunning
= true;
71 await chore
.choreFn(...choreArgs
);
73 this.logger
.error(_scope
, 'chore failed', { choreName
, error: e
});
74 if (choreArgs
.length
) {
75 // If args were supplied, was invoked off-schedule, propagate the error.
79 chore
.isRunning
= false;
80 if (chore
.intervalMs
) {
81 chore
.timeoutObj
.refresh();
82 chore
.nextSchedule
= new Date(Date
.now() + chore
.intervalMs
);
88 * Stop a chore from being scheduled to run.
89 * @param {String} choreName
91 stopChore(choreName
) {
92 const _scope
= _fileScope('stopChore');
94 const chore
= this._getChore(choreName
);
95 clearTimeout(chore
.timeoutObj
);
96 chore
.timeoutObj
= undefined;
97 chore
.nextSchedule
= undefined;
98 this.logger
.debug(_scope
, 'stopped chore', { chore
});
102 for (const choreName
in this.chores
) {
103 this.stopChore(choreName
);
109 module
.exports
= Chores
;