workerState.js 1.4 KB

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