ChildPoolJob
ee-core:v2.1.0
# 介绍
ChildPoolJob基于node.js子进程实现。可以创建一批进程常驻内存,传递任务后直接执行,没有创建、销毁进程的性能开销,延迟低。
注意:node.js子进程中无法使用所有涉及electron的api(electron技术本身无法支持),相关业务请写在主进程
# 目录
./electron/jobs
# 使用方法
- 编写任务代码
const Job = require('ee-core/jobs/baseJobClass');
const Loader = require('ee-core/loader');
const Log = require('ee-core/log');
const Ps = require('ee-core/ps');
const { childMessage } = require('ee-core/message');
const Hello = require('./hello');
/**
* example - TimerJob
* @class
*/
class TimerJob extends Job {
constructor(params) {
super();
this.params = params;
}
/**
* handle()方法是必要的,且会被自动调用
*/
async handle () {
Log.info("[child-process] TimerJob params: ", this.params);
// 计时器任务
let number = 0;
let jobId = this.params.jobId;
let eventName = 'job-timer-progress-' + jobId;
let timer = setInterval(function() {
Hello.welcome();
childMessage.send(eventName, {jobId, number, end: false});
number++;
}, 1000);
// 用 setTimeout 模拟任务运行时长
setTimeout(() => {
// 关闭定时器
clearInterval(timer);
// 任务结束,重置前端显示
childMessage.send(eventName, {jobId, number:0, pid:0, end: true});
// 如果是childJob任务,必须调用 Ps.exit() 方法,让进程退出,否则会常驻内存
// 如果是childPoolJob任务,常驻内存,等待下一个业务
if (Ps.isChildJob()) {
Ps.exit();
}
}, 10 * 1000)
}
}
TimerJob.toString = () => '[class TimerJob]';
module.exports = TimerJob;
- 触发任务
# ./electron/service/example.js
# 引入模块
const { ChildPoolJob } = require('ee-core/jobs');
/**
* 示例服务(service层为单例)
* @class
*/
class ExampleService extends Service {
constructor(ctx) {
super(ctx);
// 在构造函数中初始化一些变量
this.myJobPool = new ChildPoolJob();
}
/**
* 创建pool
*/
doCreatePool(num, event) {
const channel = 'controller.example.createPoolNotice';
this.myJobPool.create(num).then(pids => {
event.reply(`${channel}`, pids);
});
}
/**
* 通过进程池执行任务
*/
doJobByPool(jobId, action, event) {
let res = {};
const channel = 'controller.example.timerJobProgress';
if (action == 'run') {
// 异步-执行任务及监听进度
this.myJobPool.runPromise('./jobs/example/timer', {jobId}).then(task => {
// 监听器名称唯一,否则会出现重复监听。
// 任务完成时,需要移除监听器,防止内存泄漏
let eventName = 'job-timer-progress-' + jobId;
task.emitter.on(eventName, (data) => {
Log.info('[main-process] [ChildPoolJob] timerTask, from TimerJob data:', data);
// 发送数据到渲染进程
event.sender.send(`${channel}`, data)
// 如果收到任务完成的消息,移除监听器
if (data.end) {
task.emitter.removeAllListeners(eventName);
}
});
res.pid = task.pid;
});
}
return res;
}
}
ExampleService.toString = () => '[class ExampleService]';
module.exports = ExampleService;
上次更新: 2025/03/27, 02:12:08