Skip to content

Commit

Permalink
docs(pattern): add timeout section
Browse files Browse the repository at this point in the history
  • Loading branch information
roggervalf committed Nov 15, 2023
1 parent 517d011 commit cf17cd6
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 2 deletions.
1 change: 1 addition & 0 deletions docs/gitbook/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
* [Process Step Jobs](patterns/process-step-jobs.md)
* [Failing fast when Redis is down](patterns/failing-fast-when-redis-is-down.md)
* [Stop retrying jobs](patterns/stop-retrying-jobs.md)
* [Timeout](patterns/timeout.md)

## BullMQ Pro

Expand Down
64 changes: 64 additions & 0 deletions docs/gitbook/patterns/timeout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Timeout

Sometimes, it is useful to timeout a processor function but you should be aware that async processes are not going to be cancelled immediately, even if you timeout a process, you need to validate that your process is in a cancelled state:

```typescript
enum Step {
Initial,
Second,
Finish,
}

const worker = new Worker(
'queueName',
async job => {
let { step, timeout } = job.data;
let timeoutReached = false;

setTimeout(() => {
timeoutReached = true;
}, timeout);
while (step !== Step.Finish) {
switch (step) {
case Step.Initial: {
await doInitialStepStuff(1000);
if (timeoutReached) {
throw new Error('Timeout');
}
await job.updateData({
step: Step.Second,
timeout,
});
step = Step.Second;
break;
}
case Step.Second: {
await doSecondStepStuff();
if (timeoutReached) {
throw new Error('Timeout');
}
await job.updateData({
step: Step.Finish,
timeout,
});
step = Step.Finish;
return Step.Finish;
}
default: {
throw new Error('invalid step');
}
}
}
},
{ connection },
);
```

{% hint style="info" %}
It's better to split a long process into little functions/steps to be able to stop an execution by validating if we reach the timeout in each transition.
{% endhint %}

## Read more:

- 📋 [Process Step jobs](./process-step-jobs.md)
- 📋 [Cancellation by using Observables](../bullmq-pro/observables/cancelation.md)
2 changes: 0 additions & 2 deletions tests/test_worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2577,13 +2577,11 @@ describe('workers', function () {
setTimeout(() => {
timeoutReached = true;
}, timeout);
console.log(step, timeoutReached, job.data.timeout);
while (step !== Step.Finish) {
switch (step) {
case Step.Initial: {
await delay(1000);
if (timeoutReached) {
console.log('reaached1');
throw new Error('Timeout');
}
await job.updateData({
Expand Down

0 comments on commit cf17cd6

Please sign in to comment.