Skip to content

Cron

Cron triggers let you schedule code to run repeatedly on a schedule.

Some common examples include:

  • Checking an RSS feed every hour
  • Getting notified when a website updates
  • Sending a reminder email every morning

Crons can be configured with cron syntax, or simple intervals like “once an hour”

To add a cron trigger, click the + button in the top right of your val editor and select CRON.

add cron trigger

Functions can run up to once every 15 minutes, or once a minute, with the Pro plan.

Crons take an Interval object as a parameter, and can return anything as a result. The return value is ignored.

ExampleRun in Val Town ↗
export function cronValHandler(interval: Interval) {
console.log("Cron val ran!");
}

The Interval type has the following shape:

interface Interval {
lastRunAt: Date | undefined;
}

There are two kinds of schedules: either simple intervals, like “run every two hours”, or you can use cron syntax to define more complex schedules.

You can consult crongpt.com for help on writing cron expressions. For example the following cron runs every two hours, on the first day of the month:

0 */2 1 * *

This example polls an RSS feed for new items since the last run. This val runs every 1 hour.

View and run this example on Val Town

import { getLegacyImportUrl } from "https://esm.town/v/std/getLegacyImportUrl/main.tsx";
import { blob } from "https://esm.town/v/std/blob?v=12";
import { email } from "https://esm.town/v/std/email?v=12";
import RssParser from "npm:rss-parser";
export async function rssNotify() {
const lastRunAt = await blob.getJSON(getLegacyImportUrl(import.meta.url));
console.log(`Last run: ${lastRunAt || "Never"}`);
await blob.setJSON(getLegacyImportUrl(import.meta.url), new Date());
const feed = await new RssParser().parseURL("https://www.inkandswitch.com/index.xml");
console.log(`There are ${feed.items.length} items in the RSS feed`);
const newItems = feed.items.filter(
(item) => lastRunAt ? new Date(item.pubDate) > new Date(lastRunAt) : true,
);
console.log(`There are ${newItems.length} new items in the RSS feed`);
// if there are new items, email them to me
if (newItems.length > 0) {
await email({
subject: `There are ${newItems.length} new items in the RSS feed`,
html: newItems.map((item) => `<p><a href="${item.link}">${item.title}</a></p>`).join(""),
});
}
}