#stop running if already running
1 messages · Page 1 of 1 (latest)
Hi @rocky mortar. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To address your question about stopping a batch of functions from being kicked off again if they're still running in the background, Convex provides a few ways to handle this scenario. Here's how you can approach it:
- Tracking status in a table:
You can create a table to keep track of the status of your long-running tasks. This approach allows you to check if a task is already in progress before starting a new one.
Stack > Background Job Management provides an example of how to implement this:
submissions: defineTable({
prompt: v.string(),
authorId: v.id("users"),
result: v.union(
v.object({
status: v.literal("generating"),
details: v.string(),
}),
v.object({
status: v.literal("failed"),
reason: v.string(),
elapsedMs: v.number(),
}),
v.object({
status: v.literal("saved"),
imageStorageId: v.string(),
elapsedMs: v.number(),
})
),
}),
You can update the status as your functions progress and check this status before starting new tasks.
- Retrieving scheduled function status:
Convex allows you to query the status of scheduled functions using the system table"_scheduled_functions".
Scheduling > Scheduled Functions > Retrieving scheduled function status shows how to do this:
export const getScheduledMessage = query({
args: {
id: v.id("_scheduled_functions"),
},
handler: async (ctx, args) => {
return await ctx.db.system.get(args.id);
},
});
You can use this to check if your functions are still running before starting a new batch.
- Cancelling scheduled functions:
If you need to cancel previously scheduled functions, you can use thecancelmethod from the scheduler:
Scheduling > Scheduled Functions > Canceling scheduled functions provides an example:
export const cancelMessage = mutation({
args: {
id: v.id("_scheduled_functions"),
},
handler: async (ctx, args) => {
await ctx.scheduler.cancel(args.id);
},
});
By combining these approaches, you can create a system where you check the status of your batch processing functions before starting new ones, and cancel or prevent new batches from starting if the previous ones are still running.