Skip to content

Instantly share code, notes, and snippets.

@nori3tsu
Last active August 5, 2019 06:02
Show Gist options
  • Save nori3tsu/b1a6ce4ff564b3e685804e833d7ea217 to your computer and use it in GitHub Desktop.
Save nori3tsu/b1a6ce4ff564b3e685804e833d7ea217 to your computer and use it in GitHub Desktop.
This is an example of job queue by JavaScript.
import * as log from 'loglevel'
export default class JobQueue {
constructor (name, options) {
this._name = name
this._queue = []
this._running = false
this._options = Object.assign({ interval: 1000 }, options)
}
enqueue (task) {
this._queue.push(task)
}
start () {
setInterval(async () => {
if (this._running) {
return
}
const task = this._queue.pop()
if (!task) {
return
}
this._queue = []
this._running = true
try {
log.info(`${this._name}: ジョブを実行`)
await task()
} catch (error) {
log.info(`${this._name}: エラー発生`)
log.error(error.stack)
} finally {
this._running = false
}
}, this._options.interval)
}
}
import JobQueue from './JobQueue'
const queue = new JobQueue('my job')
queue.start()
for (let i = 0; i < 10; i++) {
queue.enqueue(() => {
// execute your async task!!
// return executeAsync()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment