You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.3 KiB
60 lines
1.3 KiB
import cron from 'node-cron';
|
|
|
|
class Scheduler {
|
|
constructor() {
|
|
this.jobs = new Map();
|
|
}
|
|
|
|
add(id, cronTime, task, options = {}) {
|
|
if (this.jobs.has(id)) this.remove(id);
|
|
const job = cron.createTask(cronTime, task, { ...options, noOverlap: true });
|
|
this.jobs.set(id, { job, cronTime, task, options, status: 'stopped' });
|
|
}
|
|
|
|
execute(id) {
|
|
const entry = this.jobs.get(id);
|
|
if (entry && entry.status === 'running') {
|
|
entry.job.execute();
|
|
}
|
|
}
|
|
|
|
start(id) {
|
|
const entry = this.jobs.get(id);
|
|
if (entry && entry.status !== 'running') {
|
|
entry.job.start();
|
|
entry.status = 'running';
|
|
}
|
|
}
|
|
|
|
stop(id) {
|
|
const entry = this.jobs.get(id);
|
|
if (entry && entry.status === 'running') {
|
|
entry.job.stop();
|
|
entry.status = 'stopped';
|
|
}
|
|
}
|
|
|
|
remove(id) {
|
|
const entry = this.jobs.get(id);
|
|
if (entry) {
|
|
entry.job.destroy();
|
|
this.jobs.delete(id);
|
|
}
|
|
}
|
|
|
|
updateCronTime(id, newCronTime) {
|
|
const entry = this.jobs.get(id);
|
|
if (entry) {
|
|
this.remove(id);
|
|
this.add(id, newCronTime, entry.task, entry.options);
|
|
}
|
|
}
|
|
|
|
list() {
|
|
return Array.from(this.jobs.entries()).map(([id, { cronTime, status }]) => ({
|
|
id, cronTime, status
|
|
}));
|
|
}
|
|
}
|
|
|
|
export default new Scheduler();
|
|
|