#can we call sceheduler from within mutation?

1 messages · Page 1 of 1 (latest)

ashen shuttle
#

x

clear ridgeBOT
#

Hi @ashen shuttle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can call the scheduler from within a mutation in Convex. This is a common and recommended pattern, especially when you need to perform side effects (like calling external APIs) after a mutation has successfully committed. You do this using ctx.scheduler.runAfter or ctx.scheduler.runAt inside your mutation's handler. For example:

export const sendExpiringMessage = mutation({
  args: { body: v.string(), author: v.string() },
  handler: async (ctx, args) => {
    const { body, author } = args;
    const id = await ctx.db.insert("messages", { body, author });
    await ctx.scheduler.runAfter(5000, internal.messages.destruct, {
      messageId: id,
    });
  },
});

This ensures that the scheduled function (like deleting a message) will only be scheduled if the mutation succeeds. If the mutation fails, nothing is scheduled. This pattern is also used to schedule actions for side effects, such as calling third-party APIs, since mutations themselves must remain deterministic and cannot perform such side effects directly Scheduled Functions Using Pinecone and Embeddings.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: