BullMQ
Search…
Manually processing jobs
When a Worker is instantiated, the most common usage is to specify a process function so that the worker will automatically process the jobs that arrive to the queue.
Sometimes however it is useful to be able to fetch the jobs manually. Just instantiate the worker without a processor and call getNextJob to fetch the next job:
1
const worker = new Worker('my-queue');
2
3
// Specify a unique token
4
const token = 'my-token';
5
6
const job = (await worker.getNextJob(token)) as Job;
7
8
// Access job.data and do something with the job
9
// processJob(job.data)
10
if (succeeded) {
11
await job.moveToCompleted('some return value', token);
12
} else {
13
await job.moveToFailed(new Error('my error message'), token);
14
}
15
16
await worker.close();
Copied!
There is an important consideration regarding job "locks" when processing manually. Locks avoid other workers to fetch the same job that is being processed by a given worker. The ownership of the lock is determined by the "token" that is sent when getting the job.
the lock duration setting is called "visibility window" in other queue systems.
Normally a job gets locked as soon as it is fetched from the queue with a max duration of "lockDuration" worker option. The default is 30 seconds but can be changed to any value easily, for example, to change it to 60 seconds:
1
const worker = new Worker('my-queue', null, { lockDuration: 60000 });
Copied!
When using standard worker processors the lock is renewed automatically after half lock duration time has passed, however, this mechanism does not exist when processing jobs manually, so you need to make sure to process the job faster than the lockDuration to avoid the "QueueScheduler" to move the job back to the waiting list of the queue or you can extend the lock for the job manually:
1
const job = (await worker.getNextJob(token)) as Job;
2
3
// Extend the lock 30 more seconds
4
await job.extendLock(token, 30000);
Copied!

Looping through jobs

In many cases, you will have an "infinite" loop that processes jobs one by one like this example:
1
const worker = new Worker('my-queue');
2
3
const token = 'my-token';
4
let job;
5
6
while (1) {
7
let jobData = null,
8
jobId,
9
success;
10
11
if (job) {
12
// Use job.data to process this particular job.
13
// and set success variable if succeeded
14
15
if (success) {
16
[jobData, jobId] = await job.moveToCompleted('some return value', token);
17
} else {
18
await job.moveToFailed(new Error('some error message'), token);
19
}
20
21
if (jobData) {
22
job = Job.fromJSON(worker, jobData, jobId);
23
} else {
24
job = null;
25
}
26
} else {
27
if (!job) {
28
job = await worker.getNextJob(token);
29
}
30
}
31
}
Copied!
Copy link