Skip to content

Instantly share code, notes, and snippets.

@moltar
Created June 20, 2018 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moltar/f9e5843d2c04e3f6e5fd789c18ad3b9c to your computer and use it in GitHub Desktop.
Save moltar/f9e5843d2c04e3f6e5fd789c18ad3b9c to your computer and use it in GitHub Desktop.
Assure bull only runs a single instance of a job
global.Promise = require('bluebird')
const Queue = require('bull')
const EventEmitter = require('events')
const JOB_NAME = 'testJob'
const PROGRESS_BUS_EVENT_NAME = 'progress'
const COMPLETED_PROGRESS_VALUE = 100
const { log } = console
const q = new Queue('testing')
const progressBus = new EventEmitter()
q.process(JOB_NAME, job => new Promise((resolve, reject) => {
log('Processing job %s; Counter: %d', job.id, job.data.count)
progressBus.on(PROGRESS_BUS_EVENT_NAME, (data) => {
if (job.id === data.job.id && data.progress === COMPLETED_PROGRESS_VALUE) {
Promise
.resolve()
.then(() => {
// do async job cleanup here (optionally)
})
.then(() => resolve({ status: 'superseded' }))
}
})
setTimeout(() => {
resolve({ status: 'completed' })
}, 5000)
}))
q.on('progress', (job, progress) => {
log('Job %s progress changed to %d.', job.id, progress)
progressBus.emit(PROGRESS_BUS_EVENT_NAME, { job, progress })
})
q.on('completed', (job, res) => {
log('Job %s had completed with status `%s`.', job.id, res.status)
})
q.add(JOB_NAME, { count: 1 })
setTimeout(() => {
q
.getActive()
.map((job) => {
if (job.name === JOB_NAME) {
job.progress(COMPLETED_PROGRESS_VALUE)
}
return job
})
.then(() => q.add(JOB_NAME, { count: 2 }))
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment