Navigated to /docs/endpoints/scheduled-functions.

Scheduled functions

Trigger server functions on a schedule of your choosing

Endpoints defined in server/endpoints are triggered in response to HTTP requests made by your application's frontend or by your users directly. You can also create "scheduled" backend functions that run periodically. These functions live inside files within the server/schedules directory. Functions can be defined in either JavaScript or TypeScript files.

Setting the schedule

Scheduled functions use the same file-based routing your Nokkio application uses elsewhere, with each depth of the route indicating what day of the week, hour, and minute you wish your function to be called on. In this example, the function defined in the default export of 15.js will run every Sunday at 12:15 UTC.

server/schedules
└── 00
    └── 12
        └── 15.js

Using wildcards

For functions to run every day, hour, and/or minute, use a parameterized route for the segment that will act as a wildcard. Expanding our example above, this creates a second scheduled route that runs every day at 12:15 UTC:

server/schedules
├── [day]
│   └── 12
│   │   └── 15.js
└── 00
    └── 12
        └── 15.js

Similarly, use [hour] and [minute] to run functions every hour and/or minute. This example adds a scheduled function that runs every day, every hour, at 15 minutes past the top of the hour, and another that executes every minute of every day.

server/schedules
├── [day]
│   ├── 12
│   │   └── 15.js
│   └── [hour]
│   │   ├── 15.js
│   │   └── [minute].js
└── 00
    └── 12
        └── 15.js

Scheduled function contract

Inside your scheduled function module, the only requirement is to export a function as the default export. If your function performs async operations, make sure the default export also returns a Promise so Nokkio will wait until all operations are complete before terminating the function.

server/schedules/00/12/15.js
export default function () {
  // your logic here
}

Your scheduled functions have access to the same functionality as endpoints, including secrets, writing files, and your data models. See the writing endpoints guide for more detail.

Getting the scheduled date at runtime

When using wildcard segments, it may be useful to know what date has triggered the scheduled function. Your function will be passed a date in the first argument. This date is the exact date and time that matched your schedule, not the time of execution itself (which may be several seconds later).

server/schedules/00/[hour]/15.ts
export default function ({ date }: { date: Date }) {
  // when this function is triggered at 12 UTC
  // date.getHour() will be 12 in this case
}

Real world example

bedtime-ai.nokk.io is a Nokkio demo that integrates with the OpenAI API to create bedtime stories for children. It uses a scheduled function to create a new featured story every day.

The code is available on GitHub, including the logic for the scheduled function.