up
This commit is contained in:
57
src/lib/schedule.ts
Normal file
57
src/lib/schedule.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
class SimpleSchedule {
|
||||
|
||||
private task_is_running: boolean;
|
||||
private taskCaller: () => Promise<any>;
|
||||
private trackInterval: NodeJS.Timeout | null;
|
||||
private checkInterval: number; //default
|
||||
|
||||
constructor(taskFn: () => Promise<any>, checkInterval: number = 5) {
|
||||
this.taskCaller = taskFn;
|
||||
this.task_is_running = false;
|
||||
this.trackInterval = null;
|
||||
this.checkInterval = checkInterval;
|
||||
}
|
||||
|
||||
start = () => {
|
||||
console.log(`Schedule ${this.taskCaller.name} started at ${this.timeNow()}`);
|
||||
|
||||
this.trackInterval = setInterval(async () => {
|
||||
// flag for long-running task so another instance wont start
|
||||
if(this.task_is_running) {
|
||||
console.log(`Task ${this.taskCaller.name} is still running. Check time ${this.timeNow()}`);
|
||||
return;
|
||||
}
|
||||
|
||||
this.task_is_running = true;
|
||||
console.log(`OK invoke ${this.taskCaller.name} at ${this.timeNow()}`);
|
||||
await this.taskCaller();
|
||||
this.task_is_running = false;
|
||||
}, this.checkInterval * 1000 );
|
||||
}
|
||||
|
||||
getInterval = (): number => this.checkInterval;
|
||||
|
||||
changeInterval = (new_interval: number) => {
|
||||
if(new_interval === this.checkInterval) {
|
||||
return; // nothing change!
|
||||
}
|
||||
|
||||
// remove running
|
||||
if(this.trackInterval) clearInterval(this.trackInterval);
|
||||
|
||||
// set and start
|
||||
this.checkInterval = new_interval;
|
||||
this.start();
|
||||
}
|
||||
|
||||
stop = () => {
|
||||
console.log(`Schedule ${this.taskCaller.name} stoped at ${this.timeNow()}`);
|
||||
if(this.trackInterval) clearInterval(this.trackInterval);
|
||||
}
|
||||
|
||||
timeNow = () => {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
export default SimpleSchedule;
|
||||
Reference in New Issue
Block a user