taskbuffer/ts/taskbuffer.classes.taskmanager.ts

98 lines
2.3 KiB
TypeScript
Raw Normal View History

2017-06-09 21:33:41 +00:00
import * as plugins from './taskbuffer.plugins'
2017-06-17 14:56:33 +00:00
import { Task } from './taskbuffer.classes.task'
// interfaces
import { Objectmap } from 'lik'
export class TaskManager {
taskMap = new plugins.lik.Objectmap<Task>()
2017-06-18 11:25:09 +00:00
private cronJobMap = new plugins.lik.Objectmap<ICronJob>()
2017-06-17 14:56:33 +00:00
constructor () {
// nothing here
}
/**
* checks if a task is already present
* @param taskNameArg
*/
getTaskByName (taskNameArg): Task {
return this.taskMap.find((itemArg) => {
return itemArg.name === taskNameArg
})
}
/**
* adds a Task to the TaskManager
* @param taskArg
*/
addTask (taskArg: Task): void {
if (!taskArg.name) {
throw new Error('taskArg needs a name to be added to taskManager')
}
this.taskMap.add(taskArg)
}
/**
* adds and schedules a task at once
* @param taskArg
* @param cronStringArg
*/
addAndScheduleTask (taskArg: Task, cronStringArg: string) {
this.addTask(taskArg)
let taskName = taskArg.name
this.scheduleTaskByName(taskName, cronStringArg)
}
/**
* triggers a task in the TaskManagerByName
* @param taskNameArg
*/
2017-06-18 11:25:09 +00:00
triggerTaskByName (taskNameArg: string): Promise<any> {
2017-06-17 14:56:33 +00:00
let taskToTrigger = this.getTaskByName(taskNameArg)
if (!taskToTrigger) {
throw new Error(`There is no task with the name of ${taskNameArg}`)
}
2017-06-18 11:25:09 +00:00
return taskToTrigger.trigger()
2017-06-17 14:56:33 +00:00
}
/**
* schedules the task by name
* @param taskNameArg
*/
scheduleTaskByName (taskNameArg: string, cronStringArg: string) {
let taskToSchedule = this.getTaskByName(taskNameArg)
let job = new plugins.cron.CronJob({
cronTime: cronStringArg,
2017-06-18 11:25:09 +00:00
onTick: () => {
this.triggerTaskByName(taskNameArg)
},
2017-06-17 14:56:33 +00:00
start: true
})
2017-06-18 11:25:09 +00:00
this.cronJobMap.add({
2017-06-17 14:56:33 +00:00
taskNameArg: taskToSchedule.name,
cronString: cronStringArg,
job: job
})
}
2017-06-18 11:25:09 +00:00
descheduleTaskByName (taskNameArg: string) {
let descheduledCron = this.cronJobMap.findOneAndRemove((itemArg) => {
return itemArg.taskNameArg === taskNameArg
})
descheduledCron.job.stop()
}
2017-06-17 14:56:33 +00:00
/**
* returns all schedules of a specific task
* @param taskNameArg
*/
getSchedulesForTaskName (taskNameArg: string) {
}
}
export interface ICronJob {
cronString: string
taskNameArg: string
job: any
}