Last active
August 5, 2019 06:02
-
-
Save nori3tsu/b1a6ce4ff564b3e685804e833d7ea217 to your computer and use it in GitHub Desktop.
This is an example of job queue by JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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