Repeat Strategies
Last updated
Was this helpful?
Last updated
Was this helpful?
BullMQ comes with two predefined strategies for creating repeatable jobs. The ‘every’ strategy is straightforward, allowing you to schedule jobs to repeat at specific intervals, measured in seconds. The more complex ‘cron’ strategy uses cron expressions, as defined by the to schedule jobs in intricate patterns. Additionally, BullMQ lets you create custom strategies, giving you the flexibility to define your own logic for setting job intervals.
The every strategy is used when we simply want to produce repeatable jobs at specific intervals:
Below is the supported format for cron expressions in cron-parser:
This format includes the optional second field, which is not typically available in standard cron schedules, allowing for even more precise scheduling.
Cron expressions are quite powerful as in they support seemless handling timezone differences and daylight saving time transitions, crucial for tasks that depend on local times. And also because of the use of special characters to denote specific days or things like the last day of the month, providing flexibility for monthly and weekly tasks.
Here follows an example that sets up a job to execute at 9:00 AM from Monday to Friday:
It is possible to define a different strategy to schedule repeatable jobs. The idea is that the repeat strategy, based on a pattern and the latest job's milliseconds, return the next desired timestamp. Although not used in the following example, you could have different behaviours on your repeat strategies based on the current job's name if you want to. However not that only one repeatStrategy can be defined for a given queue.
As you may have noticed, the repeat strategy setting should be provided in both the Queue and Worker classes. The reason we need it in both places is that when we first add the job to the Queue, we need to calculate when the next iteration will occur. After that, the Worker takes over, and we use the settings configured in the Worker.
The “cron” strategy in BullMQ leverages the library to use cron expressions for scheduling jobs with greater specificity. This approach is ideal for jobs requiring execution at precise times or intervals, such as automated reports or maintenance tasks.
If you are new to Cron expressions, is an excelent starting point to learn how to use them.
For example we can create a custom one for like this: