Skip to content

Instantly share code, notes, and snippets.

@felixmosh
Created May 27, 2021 08:07
Show Gist options
  • Save felixmosh/e0b207a5c6e8aefd40a871f028d09179 to your computer and use it in GitHub Desktop.
Save felixmosh/e0b207a5c6e8aefd40a871f028d09179 to your computer and use it in GitHub Desktop.
Fake progress update for bullMQ worker
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);
}
};
}
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();
});
@felixmosh
Copy link
Author

This Gists uses the same fake progress function as nprogress does.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment