import { Application } from 'egg' ; import { Job , scheduleJob , cancelJob } from 'node-schedule' ; import { ISchedulerJobHandler , ISchedulerJobCallback } from './types' ; export class AgentWorkerJobHandler implements ISchedulerJobHandler { private app : Application ; private name : string ; private time : string ; private func : ISchedulerJobCallback ; private job : Job ; constructor ( app , name , time , func ) { this . app = app ; this . name = name ; this . time = time ; this . func = func ; this . job = scheduleJob ( name , time , ( ) => { } ) ; this . app . event . publish ( 'agent' , SchedulerWorkerRegisterEvent , { name : this . name , time : this . time , } ) ; } public cancel ( ) { this . app . event . publish ( 'agent' , SchedulerWorkerUpdateEvent , { name : this . name , type : 'cancel' , } ) ; this . job . cancel ( ) ; cancelJob ( this . job ) ; } public reschedule ( time ) { this . time = time ; this . job . reschedule ( time ) ; this . app . event . publish ( 'agent' , SchedulerWorkerUpdateEvent , { name : this . name , type : 'update' , time : this . time , } ) ; } public nextScheduleTime ( ) { return this . job . nextInvocation ( ) ; } public invoke ( ) { this . func ( new Date ( ) ) ; } } export class SchedulerWorkerRegisterEvent { public name : string ; public time : string ; } export class SchedulerAgentScheduleEvent { public name : string ; } export class SchedulerWorkerUpdateEvent { public name : string ; public type : 'update' | 'cancel' ; public time ? : string ; }