WorkerState.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const utils = require('./utils');
  2. const cleanInterval = 3600; //sec
  3. const cleanAfterLastModified = cleanInterval - 60; //sec
  4. let instance = null;
  5. //singleton
  6. class WorkerState {
  7. constructor() {
  8. if (!instance) {
  9. this.states = {};
  10. this.cleanStates();
  11. instance = this;
  12. }
  13. return instance;
  14. }
  15. generateWorkerId() {
  16. return utils.randomHexString(20);
  17. }
  18. getControl(workerId) {
  19. return {
  20. set: state => this.setState(workerId, state),
  21. finish: state => this.finishState(workerId, state),
  22. get: () => this.getState(workerId),
  23. };
  24. }
  25. setState(workerId, state) {
  26. this.states[workerId] = Object.assign({}, this.states[workerId], state, {
  27. workerId,
  28. lastModified: Date.now()
  29. });
  30. }
  31. finishState(workerId, state) {
  32. this.states[workerId] = Object.assign({}, this.states[workerId], state, {
  33. workerId,
  34. state: 'finish',
  35. lastModified: Date.now()
  36. });
  37. }
  38. getState(workerId) {
  39. return this.states[workerId];
  40. }
  41. cleanStates() {
  42. const now = Date.now();
  43. for (let workerID in this.states) {
  44. if ((now - this.states[workerID].lastModified) >= cleanAfterLastModified*1000) {
  45. delete this.states[workerID];
  46. }
  47. }
  48. setTimeout(this.cleanStates.bind(this), cleanInterval*1000);
  49. }
  50. }
  51. module.exports = WorkerState;