15815213711
2024-08-26 67b8b6731811983447e053d4396b3708c14dfe3c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const EventEmitter = require('events');
const ForkProcess = require('./forkProcess');
const Loader = require('../../loader');
const Channel = require('../../const/channel');
const Conf = require('../../config/cache');
 
class ChildJob extends EventEmitter {
 
  constructor() {
    super();
    this.jobs = {};
    this.config = {};
 
    const cfg = Conf.getValue('jobs');
    if (cfg) {
      this.config = cfg;
    }
 
    this._initEvents();
  }
 
  /**
   * 初始化监听
   */  
  _initEvents() {
    this.on(Channel.events.childProcessExit, (data) => {
      delete this.jobs[data.pid];
    });
    this.on(Channel.events.childProcessError, (data) => {
      delete this.jobs[data.pid];
    });
  }
 
  /**
   * 执行一个job文件
   */  
  exec(filepath, params = {}, opt = {}) {
    const jobPath = Loader.getFullpath(filepath);
    const proc = this.createProcess(opt);
    const cmd = 'run';
    proc.dispatch(cmd, jobPath, params);
  
    return proc;
  }
 
  /**
   * 创建子进程
   */  
  createProcess(opt = {}) {
    let options = Object.assign({
      processArgs: {
        type: 'childJob'
      }
    }, opt);
    const proc = new ForkProcess(this, options);
    if (!proc) {
      let errorMessage = `[ee-core] [jobs/child] Failed to obtain the child process !`
      throw new Error(errorMessage);
    }
    this.jobs[proc.pid] = proc;
 
    return proc;
  }
 
  /**
   * 获取当前pids
   */  
  getPids() {
    let pids = Object.keys(this.jobs);
    return pids;
  }  
 
  /**
   * 异步执行一个job文件 todo this指向
   */
  async execPromise(filepath, params = {}, opt = {}) {
    return this.exec(filepath, params, opt);
  }
 
}
 
module.exports = ChildJob;