Cloud cron jobs with Netlify Scheduled Functions
By Flavio Copes
Learn how to set up cloud cron jobs with Netlify Scheduled Functions, scheduling runs with @hourly, @daily, or a cron expression in netlify.toml.
Netlify Scheduled Functions let you run a serverless function on a schedule, like a cron job, but in the cloud.
A traditional cron job needs a server that’s always on. With scheduled functions there’s no server to maintain. Netlify runs your function at the times you choose, and that’s it.
Here’s how to set them up.
Create a serverless function in netlify/functions in your repository, for example test.js:
netlify/functions/test.js
exports.handler = (event, context) => {
//do something
return { statusCode: 200 }
}
Then in netlify.toml (create this file if you don’t have it yet) configure how frequently you want this Netlify Scheduled Function to run:
[functions."test"]
schedule = "@hourly"
Alternatively you can set the schedule in the function itself, using the schedule helper from the @netlify/functions package, with no need for the netlify.toml entry:
const { schedule } = require('@netlify/functions')
const handler = (event, context) => {
//do something
return { statusCode: 200 }
}
exports.handler = schedule('@hourly', handler)
@hourly runs every hour at minute 0.
@daily runs every day at 00:00.
@weekly runs every Sunday at 00:00.
@monthly and @yearly are available too.
You can also use a cron expression, like 5 4 * * * or any other expression (crontab guru is your friend).
Watch out for the timezone
Schedules run in UTC, not in your local timezone.
I got bitten by this. I set 0 7 * * * expecting the function to run at 7 AM my time, and it ran at 7 AM UTC instead. If you need a specific local time, adjust the cron expression to the equivalent UTC time.
Also note that scheduled functions only run on the published production deploy. They don’t run on deploy previews or branch deploys, and they don’t fire while you work locally.
How to test a scheduled function
You don’t want to wait an hour to see if your function works.
Using the Netlify CLI you can invoke it manually with netlify functions:invoke test, where test is the name of the function.
One more thing: nobody receives the response of a scheduled function. Netlify only uses the status code for logging, so return { statusCode: 200 } to mark a successful run and log anything you need with console.log().
What I use them for
You can use Netlify Scheduled Functions for many different use cases.
I set a Netlify Scheduled Function to auto-deploy the repository every day to publish scheduled blog posts, for which I set the publishing date in advance.
I use the Fetch API to call the deploy webhook so I can do automatic deploys on Netlify.
Related posts about services: