import { Agent } from 'egg' ; import { scheduleJob , Job , cancelJob } from 'node-schedule' ; import { BasicJobHandler } from './BasicJobHandler' ; import { SchedulerWorkerRegisterEvent , SchedulerWorkerUpdateEvent , SchedulerAgentScheduleEvent } from './AgentWorkerJobHandler' ; import { AgentPluginBase } from '../../basic/AgentPluginBase' ; import { ISchedulerJobCallback , ISchedulerJobHandler } from './types' ; export class AgentSchedulerManager extends AgentPluginBase < null > { private workerHandlerMap : Map < string , Job > ; constructor ( config , agent ) { super ( config , agent ) ; this . workerHandlerMap = new Map < string , Job > ( ) ; } public async onReady ( ) { this . agent . event . subscribe ( SchedulerWorkerRegisterEvent , async ( e ) => { if ( this . workerHandlerMap . has ( e . name ) ) return ; const job = scheduleJob ( e . name , e . time , ( ) => { this . agent . event . publish ( 'worker' , SchedulerAgentScheduleEvent , { name : e . name , } ) ; } ) ; this . workerHandlerMap . set ( e . name , job ) ; } ) ; this . agent . event . subscribe ( SchedulerWorkerUpdateEvent , async ( e ) => { const job = this . workerHandlerMap . get ( e . name ) ; if ( ! job ) return ; switch ( e . type ) { case 'cancel' : this . workerHandlerMap . delete ( e . name ) ; job . cancel ( ) ; cancelJob ( job ) ; break ; case 'update' : if ( e . time ) { job . reschedule ( e . time ) ; } break ; default : break ; } } ) ; } public async onStart ( ) { } public async onClose ( ) { } register ( name , time , func ) { const schedJob = scheduleJob ( name , time , func ) ; const job = new BasicJobHandler ( schedJob ) ; return job ; } }