diff options
author | Brandon Millman <brandon.millman@gmail.com> | 2018-02-07 07:15:24 +0800 |
---|---|---|
committer | Brandon Millman <brandon.millman@gmail.com> | 2018-02-07 09:39:49 +0800 |
commit | d9b1d31e7310f7f554f1740f93e4ccd5b5db90f5 (patch) | |
tree | a76901e3d371fd3a0b27b383b4ac8a1d2dcf6fa7 /packages/testnet-faucets/src/ts/dispatch_queue.ts | |
parent | 562bcb85710c281d817c7dd4957f0a7db1ddc306 (diff) | |
download | dexon-sol-tools-d9b1d31e7310f7f554f1740f93e4ccd5b5db90f5.tar dexon-sol-tools-d9b1d31e7310f7f554f1740f93e4ccd5b5db90f5.tar.gz dexon-sol-tools-d9b1d31e7310f7f554f1740f93e4ccd5b5db90f5.tar.bz2 dexon-sol-tools-d9b1d31e7310f7f554f1740f93e4ccd5b5db90f5.tar.lz dexon-sol-tools-d9b1d31e7310f7f554f1740f93e4ccd5b5db90f5.tar.xz dexon-sol-tools-d9b1d31e7310f7f554f1740f93e4ccd5b5db90f5.tar.zst dexon-sol-tools-d9b1d31e7310f7f554f1740f93e4ccd5b5db90f5.zip |
Organize async task queues by network
Diffstat (limited to 'packages/testnet-faucets/src/ts/dispatch_queue.ts')
-rw-r--r-- | packages/testnet-faucets/src/ts/dispatch_queue.ts | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/packages/testnet-faucets/src/ts/dispatch_queue.ts b/packages/testnet-faucets/src/ts/dispatch_queue.ts new file mode 100644 index 000000000..94d094203 --- /dev/null +++ b/packages/testnet-faucets/src/ts/dispatch_queue.ts @@ -0,0 +1,47 @@ +import { intervalUtils } from '@0xproject/utils'; +import * as _ from 'lodash'; + +const MAX_QUEUE_SIZE = 500; +const DEFAULT_QUEUE_INTERVAL_MS = 1000; + +export class DispatchQueue { + private _queueIntervalMs: number; + private _queue: Array<() => Promise<void>>; + private _queueIntervalIdIfExists?: NodeJS.Timer; + constructor() { + this._queueIntervalMs = DEFAULT_QUEUE_INTERVAL_MS; + this._queue = []; + this._start(); + } + public add(task: () => Promise<void>): boolean { + if (this.isFull()) { + return false; + } + this._queue.push(task); + return true; + } + public size(): number { + return this._queue.length; + } + public isFull(): boolean { + return this.size() >= MAX_QUEUE_SIZE; + } + public stop() { + if (!_.isUndefined(this._queueIntervalIdIfExists)) { + intervalUtils.clearAsyncExcludingInterval(this._queueIntervalIdIfExists); + } + } + private _start() { + this._queueIntervalIdIfExists = intervalUtils.setAsyncExcludingInterval( + async () => { + const task = this._queue.shift(); + if (_.isUndefined(task)) { + return Promise.resolve(); + } + await task(); + }, + this._queueIntervalMs, + _.noop, + ); + } +} |