This tutorial guides you through creating an Azure Function that runs on a timer using JavaScript. Timer triggers are useful for scheduling recurring tasks, such as data cleanup, sending out notifications, or executing batch processes.
Open your terminal or command prompt and use the Azure Functions Core Tools to create a new project:
func init MyTimerProject --javascript
cd MyTimerProject
This command initializes a new JavaScript Functions project named MyTimerProject
.
Create a new function within your project using the timer trigger template:
func new --name TimerTriggerJS --template "Timer trigger"
This creates a new function named TimerTriggerJS
with the necessary files.
Open the TimerTriggerJS/function.json
file to configure the timer's schedule using a CRON expression. By default, it's set to run every minute.
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */1 * * * *",
"runOnStartup": false
},
{
"name": "myOutput",
"type": "blob",
"direction": "out",
"path": "samples-output/output-{datetime}.txt",
"connection": "AzureWebJobsStorage"
}
]
}
The schedule
property defines when the function runs. The example 0 */1 * * * *
means "at second 0 of every 1st minute of every hour of every day". You can customize this to your needs. For example, to run every 5 minutes, you could use 0 */5 * * * *
.
second minute hour day-of-month month day-of-week
.
ss mm HH * * *
(runs every hour at second ss and minute mm).
Open the TimerTriggerJS/index.js
file and add your JavaScript logic.
module.exports = async function (context, myTimer) {
const timeStamp = new Date().toISOString();
if (myTimer.isPastDue) {
context.log('JavaScript isPastDue!');
}
context.log('JavaScript timer trigger function ran at!', timeStamp);
// Example: You can write to a blob output binding
// context.bindings.myOutput = `Timer executed at: ${timeStamp}`;
};
This script logs the timestamp when the function runs. The myTimer
object provides information about the timer trigger, including whether it's past due.
Start the Azure Functions host from your project directory:
func start
You should see output in your terminal indicating that the timer trigger is active and will run according to the schedule defined in function.json
.
Once you're ready, you can deploy your function app to Azure. Make sure you have logged in using az login
.
func azure functionapp publish <YourFunctionAppName>
Replace <YourFunctionAppName>
with the name you want for your function app in Azure. Ensure you have configured application settings for any necessary connections (e.g., AzureWebJobsStorage
).
AzureWebJobsStorage
connection string is properly configured in the function app's application settings. This is typically the same storage account used by the Functions runtime.