//1. create a DynamicSchedule
const dynamicSchedule = client.defineDynamicSchedule({
id: "dynamicinterval",
});
//2. create a Job that is attached to the dynamic schedule
client.defineJob({
id: "user-dynamicinterval",
name: "User Dynamic Interval",
version: "0.1.1",
//3. set the DynamicSchedule as the Trigger
trigger: dynamicSchedule,
run: async (payload, io, ctx) => {
await io.logger.info("The userId is ", ctx.source.id);
},
});
//4. Register the DynamicSchedule anywhere in your app
async function registerUserCronJob(userId: string, userSchedule: string) {
//use the userId as the id for the DynamicSchedule
//so it comes through to run() in the context source.id
await dynamicSchedule.register(userId, {
type: "cron",
options: {
cron: userSchedule,
},
});
}
//5. Register inside other Jobs
client.defineJob({
id: "register-dynamicinterval",
name: "Register Dynamic Interval",
version: "0.1.1",
trigger: eventTrigger({
name: "dynamic.interval",
schema: z.object({
userId: z.string(),
seconds: z.number().int().positive(),
}),
}),
run: async (payload, io, ctx) => {
//6. Register the DynamicSchedule
await dynamicSchedule.register(payload.userId, {
type: "interval",
options: {
seconds: payload.seconds,
},
});
await io.wait("wait", 60);
//7. Unregister the DynamicSchedule at some later date
await dynamicSchedule.unregister(payload.userId);
},
});