Context.Executor
// @namespace Context.Executor
import { Context } from 'rcfm'
const Executor = Context.Executor
Custom Types
@typedef {Object} ExecutorInstance
@description - 任务执行器实例
Class Methods
.create()
创建一个任务执行器实例。
// Executor.create(options)
// @param {Object} options
// @prop {Function} options.runner - 一个用于批量执行任务的函数
// @returns {ExecutorInstance}
// @example - 创建任务执行器
const executor = Executor.create({
runner(jobs) {
jobs.forEach((job) => {
if (job.type === 'log') { return console.log(job.message) }
if (job.type === 'retry') {
if (job.times > 3) { return console.error(job) }
return executor.run({...job, times: (job.times || 0) + 1})
}
throw new Error('UNKNOWN_JOB_TYPE')
})
}
})
// @example - 入队任务
executor.run([{
type: 'log', message: 'Hello'
}, {
type: 'retry', times: 0
}])
executor.run({type: 'unsupported'})
Instance Methods
#abort()
更改任务执行状态为禁用或启用。当状态为禁用时,executor#run()
方法只入队任务但不再执行任务。
// executor#abort(isAborted)
// @param {boolean} [isAborted = true] - true 代表禁用,false 代表启用
// @returns {boolean} - 返回当前任务执行状态是否为禁用
// @examples
executor.abort()
executor.abort(false)
#run()
入队任务。如果任务执行函数当前空闲会立即执行入队的任务,否则会在当前队列任务执行完成后执行。
// executor#run(job)
// @param {* | *[]} [job] - 一个或多个自定义任务
// @returns {undefined}
// @example - 创建任务执行器
const executor = Executor.create({
runner(jobs) {
jobs.forEach((job) => {
if (job.type === 'log') { return console.log(job.message) }
if (job.type === 'retry') {
if (job.times > 3) { return console.error(job) }
return executor.run({...job, times: (job.times || 0) + 1})
}
throw new Error('UNKNOWN_JOB_TYPE')
})
}
})
// @example - 入队任务
executor.run([{
type: 'log', message: 'Hello'
}, {
type: 'retry', times: 0
}])
executor.run({type: 'unsupported'})