Jobs
Jobs are the functions you perform after a specific time or constantly in intervals.
Background is designed to be background job library that implement queues.
Example jobs would be the operations that you perform after a request is sent. Making too many sequential blocking operations may effect you API's performance. You may want to do some after the request is sent. You may want to use different databases for your specific jobs.
For example you usualy do not want to perform logic heavy operations in a sql based database. You usually want to do that in a process.
Here you can leverage repeatable jobs.
Some Jobs might have higher priority than others. Here you want those jobs to be processed earlier than other jobs.
Repeatable Jobs
You can repeat jobs with the addRepeatable method.
async addRepeatable<T>(
name: string,
data: T,
options: {
every: number;
unit: "seconds" | "minutes" | "hours" | "days" | "weeks" | "months";
startDate?: Date;
endDate?: Date;
limit?: number;
priority?: number;
},
): Promise<Job<T>>
Example Repeatable Job
const repeatableQueue = new JobQueue(storage, {
concurrency: 1,
processingInterval: 20,
name: 'repeatable-queue'
});
await repeatableQueue.addRepeatable(
"repeatable-job",
{ message:"hello world" },
{
every: 1,
unit: "seconds",
},
);
Prioritize Jobs
You can prioritize jobs with the priority option in the add method.
await queue.add("test-job", { message:"message" }, { priority: 10 });
Priorities are ranked from 1 to 10, 1 being the highest and 10 being lowest.
Schedule Jobs For The Future
You can schedule jobs to be run in a specific time using schedule function.
async schedule<T>(name: string, data: T, scheduledAt: Date): Promise<Job<T>>
Example Scheduled Job
const futureDate = new Date();
futureDate.setMinutes(futureDate.getMinutes() + 10); // 10 minutes in the future
const queue = new JobQueue(storage, {
concurrency: 1,
name: "test-queue",
processingInterval: 20,
});
queue.register("test-job", mockHandler);
const job = await queue.schedule(
"test-job",
{ message: "Future task" },
futureDate,
);