Skip to content

Cron

Cron is a plugin that allows you to schedule tasks.

Install

Install dependencies

cmd
bun add node-cron

Example

Run a node cron daily to send message to users

src/plugins/cron.ts
import cron from "node-cron";
import { RedisClientType } from "@redis/client";
import { XMTP } from "xmtp";
 
export async function startCron(redisClient: RedisClientType) {
  // Daily task
  const xmtp = new XMTP();
  const { v2client, v3client } = await xmtp.init();
  console.log("Starting daily cron");
  cron.schedule(
    "0 0 * * *", // Daily or every 5 seconds in debug mode
    async () => {
      const keys = await redisClient.keys("*");
      console.log(`Running daily task. ${keys.length} subscribers.`);
      for (const address of keys) {
        const subscriptionStatus = await redisClient.get(address);
        if (subscriptionStatus === "subscribed") {
          console.log(`Sending daily update to ${address}`);
          // Logic to send daily updates to each subscriber
          const conversation = await client?.conversations.newGroup([address]);
          await conversation.send("Here is your daily update!");
        }
      }
    },
    {
      scheduled: true,
      timezone: "UTC",
    },
  );
}