job.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const moment = require('moment')
  2. const childProcess = require('child_process')
  3. module.exports = class Job {
  4. constructor({
  5. name,
  6. immediate = false,
  7. schedule = 'P1D',
  8. repeat = false,
  9. worker = false
  10. }) {
  11. this.finished = Promise.resolve()
  12. this.name = name
  13. this.immediate = immediate
  14. this.schedule = moment.duration(schedule)
  15. this.repeat = repeat
  16. this.worker = worker
  17. }
  18. /**
  19. * Start Job
  20. *
  21. * @param {Object} data Job Data
  22. */
  23. start(data) {
  24. if (this.immediate) {
  25. this.invoke(data)
  26. } else {
  27. this.queue(data)
  28. }
  29. }
  30. /**
  31. * Queue the next job run according to the wait duration
  32. *
  33. * @param {Object} data Job Data
  34. */
  35. queue(data) {
  36. this.timeout = setTimeout(this.invoke.bind(this), this.schedule.asMilliseconds(), data)
  37. }
  38. /**
  39. * Run the actual job
  40. *
  41. * @param {Object} data Job Data
  42. */
  43. async invoke(data) {
  44. try {
  45. if (this.worker) {
  46. const proc = childProcess.fork(`server/core/worker.js`, [
  47. `--job=${this.name}`,
  48. `--data=${data}`
  49. ], {
  50. cwd: WIKI.ROOTPATH
  51. })
  52. this.finished = new Promise((resolve, reject) => {
  53. proc.on('exit', (code, signal) => {
  54. if (code === 0) {
  55. resolve()
  56. } else {
  57. reject(signal)
  58. }
  59. proc.kill()
  60. })
  61. })
  62. } else {
  63. this.finished = require(`../jobs/${this.name}`)(data)
  64. }
  65. await this.finished
  66. } catch (err) {
  67. WIKI.logger.warn(err)
  68. }
  69. if (this.repeat) {
  70. this.queue(data)
  71. }
  72. }
  73. /**
  74. * Stop any future job invocation from occuring
  75. */
  76. stop() {
  77. clearTimeout(this.timeout)
  78. }
  79. }