fix: Stagger built-in cron scheduler tasks within their partitionWindow (#14330)

This commit is contained in:
Tom Moor authored and GitHub committed 2026-10-24 22:18:32 -04:00
1 parent 4eca029b05
commit 8cd951afca
3 files changed
+39 -10

No files matched your search

+17
View File
@@ -80,6 +80,23 @@ describe("CronTask", () => {
}
});
it("should stay within an explicit window", () => {
const names = [
"CleanupDeletedDocumentsTask",
"CleanupOldEventsTask",
"CleanupOldSearchQueriesTask",
];
for (const name of names) {
const delay = CronTask.getStaggerDelay(
name,
TaskInterval.Hour,
Minute.ms
);
expect(delay).toBeGreaterThanOrEqual(0);
expect(delay).toBeLessThan(Minute.ms);
}
});
it("should distribute delays across the window for real task names", () => {
const names = [
"CleanupDeletedDocumentsTask",
+7 -6
View File
@@ -78,19 +78,20 @@ export abstract class CronTask extends BaseTask<Props> {
public abstract get cron(): TaskSchedule;
/**
* Compute a deterministic delay for a task based on its name and interval.
* Different tasks are likely to get different offsets within the stagger
* window for their interval, reducing concurrent heavy database operations.
* Compute a deterministic delay for a task based on its name and a stagger
* window. Different tasks are likely to get different offsets within the
* window, reducing concurrent heavy database operations.
*
* @param taskName the name of the task class.
* @param interval the task interval used to select the stagger window.
* @param interval the task interval used to select the default stagger window.
* @param windowMs an optional window in milliseconds that replaces the default.
* @returns a delay in milliseconds.
*/
public static getStaggerDelay(
taskName: string,
interval: TaskInterval
interval: TaskInterval,
windowMs = staggerWindows[interval]
): number {
const windowMs = staggerWindows[interval];
let hash = 0;
for (let i = 0; i < taskName.length; i++) {
hash = ((hash << 5) - hash + taskName.charCodeAt(i)) | 0;
+15 -4
View File
@@ -17,14 +17,25 @@ export default function init() {
}
const taskInstance = new TaskClass() as CronTask;
const { interval, partitionWindow } = taskInstance.cron;
if (taskInstance.cron.interval === schedule) {
await taskInstance.schedule({
if (interval !== schedule) {
continue;
}
// Stagger the start of tasks that define a window within that window.
const delay = partitionWindow
? CronTask.getStaggerDelay(name, interval, partitionWindow)
: 0;
await taskInstance.schedule(
{
limit: 10000,
partition,
scheduledAt,
});
}
},
{ delay }
);
}
}