Created
May 27, 2021 08:07
-
-
Save felixmosh/e0b207a5c6e8aefd40a871f028d09179 to your computer and use it in GitHub Desktop.
Fake progress update for bullMQ worker
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 { Job } from 'bullmq'; | |
import ms from 'ms'; | |
// taken from https://github.com/tanem/react-nprogress/blob/ec007096e08af79179b8530a4915e225075d37ac/src/clamp.ts | |
function clamp(num: number, lower: number, upper: number): number { | |
num = num <= upper ? num : upper; | |
num = num >= lower ? num : lower; | |
return num; | |
} | |
// taken from https://github.com/tanem/react-nprogress/blob/ec007096e08af79179b8530a4915e225075d37ac/src/increment.ts | |
function increment(progress: number): number { | |
let amount = 0; | |
if (progress >= 0 && progress < 0.2) { | |
amount = 0.1; | |
} else if (progress >= 0.2 && progress < 0.5) { | |
amount = 0.04; | |
} else if (progress >= 0.5 && progress < 0.8) { | |
amount = 0.02; | |
} else if (progress >= 0.8 && progress < 0.99) { | |
amount = 0.005; | |
} | |
return clamp(progress + amount, 0, 0.994); | |
} | |
export function startFakeProgress(job: Job) { | |
let progress = 0; | |
const id = setInterval(async () => { | |
await job.updateProgress(Math.floor(progress * 100)); | |
progress = increment(progress); | |
}, ms('1sec')); | |
return async (error?: Error) => { | |
clearInterval(id); | |
if (!error) { | |
await job.updateProgress(100); | |
} | |
}; | |
} |
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 { Worker } from 'bullmq'; | |
import { fakeProgerss } from './fakeProgress'; | |
const worker = new Worker(queueNames.predictions, async (job) => { | |
const finishWork = await startFakeProgress(job); | |
try { | |
// do your work | |
} catch (e) { | |
finishWork(e); | |
throw e; | |
} | |
finishWork(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Gists uses the same fake progress function as nprogress does.