- Triggers
- Scheduled triggers
Triggers
Scheduled triggers
Run a workflow on a recurring schedule
See the reference for more details.
Examples
Every 5 minutes
This job will run every 5 minutes, starting 5 minutes after this code is first run on your server (that includes running locally).
import { Trigger, scheduleEvent } from "@trigger.dev/sdk";
new Trigger({
id: "scheduled-workflow",
name: "Scheduled Workflow",
apiKey: "<your_api_key>",
on: scheduleEvent({ rateOf: { minutes: 5 } }),
run: async (event, ctx) => {
await ctx.logger.info("Received the scheduled event", {
event,
wallTime: new Date(),
});
return { foo: "bar" };
},
}).listen();
Using CRON syntax
This job will run at 2:30pm every Monday. You can get help with CRON syntax.
import { Trigger, scheduleEvent } from "@trigger.dev/sdk";
new Trigger({
id: "cron-scheduled-workflow",
name: "Cron Scheduled Workflow",
apiKey: "<your_api_key>",
on: scheduleEvent({ cron: "30 14 * * 1" }),
run: async (event, ctx) => {
await ctx.logger.info("Received the cron scheduled event", {
event,
wallTime: new Date(),
});
return { foo: "bar" };
},
}).listen();
Preventing late runs
To prevent a scheduled trigger from running late, you can set a triggerTTL
option when creating the Trigger
, like so:
new Trigger({
id: "scheduled-workflow",
name: "Scheduled Workflow",
apiKey: "<your_api_key>",
on: scheduleEvent({ rateOf: { minutes: 5 } }),
triggerTTL: 300,
run: async (event, ctx) => {
await ctx.logger.info("Received the scheduled event", {
event,
wallTime: new Date(),
});
return { foo: "bar" };
},
}).listen();
This will prevent the trigger from running if it is running more than 300
seconds behind, which can happen if the server running your Trigger
code goes down or is otherwise unavailable.
This is especially useful for scheduled triggers that run on a very short interval, like every minute, so you don’t get a backlog of runs that all run at once when the server comes back online.
Set your triggerTTL
to the same time (or double) as the rateOf the trigger.
Live-only scheduled events
In many cases, you only want scheduled events to run when your code is running on a server, and not locally during development. To do this, you can check the context.environment
property together with the context.isTest
property, like so:
new Trigger({
id: "check-scheduler",
name: "Check Scheduler",
on: scheduleEvent({ rateOf: { minutes: 10 } }),
logLevel: "info",
triggerTTL: 600,
run: async (event, context) => {
// Return if in development and not running a test
if (context.environment === "development" && !context.isTest) {
return;
}
// do stuff here
},
}).listen();
By checking context.isTest
, you can manually test scheduled events locally before pushing to live.