Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Serverless and Edge Functions

Scheduled and Background Functions

Run work on a schedule or after the response: Netlify Scheduled and Background Functions, Vercel Cron Jobs, cron expressions, securing cron endpoints and making jobs safe to retry.

Not every task starts with a visitor. A nightly report, a hourly cache refresh or an image-processing job that takes minutes does not fit the normal request and response pattern, because a request has a short time limit. Both platforms provide tools for this: scheduled functions that run on a clock, and background functions that continue after answering.

This lesson shows how to use each, how to read cron expressions and, most important, how to make a job safe to run twice.

Cron expressions

A schedule is written as five fields: minute, hour, day of month, month, day of week. All times are UTC on these platforms.

Expression Meaning
0 * * * * every hour, on the hour
*/15 * * * * every 15 minutes
30 2 * * * every day at 02:30 UTC
0 9 * * 1 every Monday at 09:00 UTC
0 0 1 * * midnight on the first of each month

A field can be * (any), a number, a list (1,15), a range (9-17) or a step (*/10). Day-of-week 0 or 7 is Sunday on most implementations; check the platform's docs for edge cases.

Node.js Cron matcher (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Netlify Scheduled Functions

A scheduled function is a normal function with a schedule in its config. Netlify calls it at the times you set:

JavaScript
// netlify/functions/nightly-report.js
export default async (request) => {
  const { next_run } = await request.json();   // next scheduled time is sent in the body
  console.log("Report started. Next run:", next_run);
  // ... build and send the report ...
  return new Response("done");
};

export const config = { schedule: "0 6 * * *" };   // 06:00 UTC daily

Shortcut strings such as @hourly, @daily and @weekly are accepted too. Scheduled functions run only for published production deploys, not for previews, and have a short time limit (check current docs). Test one locally with netlify functions:invoke nightly-report.

Netlify Background Functions

A background function is for work that outlasts a request. Name the file with the suffix -background (for example process-video-background.js). Netlify immediately returns an empty 202 Accepted to the caller and keeps your code running for a much longer time (the limit is far above normal functions; check current docs). The caller gets no result, so write the outcome to storage or a database and let the page check it.

JavaScript
// netlify/functions/process-video-background.js
export default async (request) => {
  const { videoId } = await request.json();
  // long work: download, transcode, upload
  // finally: write status "ready" for videoId to your database
};

Vercel Cron Jobs

Vercel runs cron jobs by calling one of your function routes on a schedule, defined in vercel.json:

JSON
{
  "crons": [
    { "path": "/api/nightly-report", "schedule": "0 6 * * *" }
  ]
}

Vercel sends an HTTP GET request to that path in the production deployment. Plans differ in how many crons you may have and how often they may run, so check your plan. Because the route is public, protect it: set an environment variable CRON_SECRET, and Vercel adds an Authorization: Bearer <secret> header to cron calls.

JavaScript
// api/nightly-report.js
export function GET(request) {
  if (request.headers.get("authorization") !== `Bearer ${process.env.CRON_SECRET}`) {
    return new Response("Unauthorized", { status: 401 });
  }
  // ... do the work ...
  return Response.json({ ok: true });
}

For long jobs on Vercel, split work into small batches, raise the function's maxDuration within plan limits, or hand the work to a queue or workflow service from the Vercel marketplace.

Node.js Securing a cron endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Make jobs safe to run twice

Schedulers and networks are imperfect: a job may run late, twice or overlap with the previous run. Design every job to be idempotent: running it again must not cause harm, such as sending the same email twice or charging a card twice. Common tools:

  1. A run key. Record "report for 2026-01-05" as done in a database, and skip if present.
  2. A lock or lease. Mark a job as running with an expiry so two runs do not overlap.
  3. Small batches. Process a limited number of items per run and continue next time.
  4. Logging. Log when each run starts and ends so you can see missed or duplicate runs.
Node.js Idempotent job with a run key (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Choosing the right tool

Need Use
Run at fixed times Scheduled Function (Netlify) or Cron Job (Vercel)
Answer fast, finish long work later Background Function (Netlify), or a queue or workflow service
Run when an event happens Webhook into a normal function
Rebuild the site on a schedule A build hook called by a cron, see rollbacks and hooks

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the cron expression */15 * * * * mean?

    A step of 15 in the minute field runs at minutes 0, 15, 30 and 45 of every hour.
  2. 2. How do you create a Netlify Background Function?

    The -background suffix makes Netlify answer 202 immediately and keep running the code.
  3. 3. Why protect a Vercel cron route with CRON_SECRET?

    Checking the Authorization header ensures only Vercel's scheduler can trigger the job.
  4. 4. What does idempotent mean for a scheduled job?

    Idempotent jobs tolerate duplicate or late triggers without repeating side effects.

Summary

  • Cron expressions have five fields (minute, hour, day, month, weekday) and run in UTC.
  • Netlify offers Scheduled Functions (config.schedule) and Background Functions (-background suffix).
  • Vercel Cron Jobs are declared in vercel.json and call a production route; secure it with CRON_SECRET.
  • Long work should return quickly and record results in storage.
  • Make every job idempotent with run keys, locks and small batches.

Next: Custom Domains and DNS