Skip to content

Cron

Cron triggers run your function automatically based on a cron expression. The function signature is the same as webhooks: every Microfn exports a main(input) function.

Endpoint is not called directly; the scheduler invokes your function with {} as input unless you configure otherwise.

  • Expression format: minute hour day month weekday (UTC)
  • Examples: * * * * * (every minute), 0 * * * * (hourly), 0 9 * * 1-5 (weekdays 09:00)
  • Configure in dashboard under Settings → Triggers
// Always export main(input)
export async function main(input: any) {
console.log("cron tick", new Date().toISOString(), input);
return { ok: true };
}
// 1) Heartbeat ping (every 5 minutes)
// Cron: */5 * * * *
export async function main() {
const res = await fetch("https://example.com/health");
return { status: res.status };
}
// 2) KV cleanup of old items (daily at 3am)
// Cron: 0 3 * * *
import kv from "@microfn/kv";
export async function main() {
const keys = (await kv.get<string[]>("cache-keys")) ?? [];
let removed = 0;
for (const k of keys) {
const item = await kv.get<{ ts: number }>(k);
if (!item || Date.now() - item.ts > 86_400_000) {
await kv.set(k, null);
removed++;
}
}
return { removed };
}
// 3) Fetch-and-store latest headline (hourly)
// Cron: 0 * * * *
import kv from "@microfn/kv";
export async function main() {
const r = await fetch("https://hn.algolia.com/api/v1/search?tags=front_page");
const j = await r.json();
const top = j.hits?.[0]?.title ?? "(none)";
await kv.set("top-headline", { title: top, ts: Date.now() });
return { title: top };
}