Timer Trigger for Azure Functions
The timer trigger is used to run a Function on a recurring schedule. It uses a cron expression or a timer interval to define the schedule.
Introduction
The timer trigger allows you to run your Azure Functions at specified intervals. This is useful for scheduled tasks, batch processing, or any scenario where you need to execute code periodically without an external HTTP request.
How it Works
The timer trigger utilizes a cron expression, a widely adopted standard for scheduling tasks. You define a schedule using a cron expression, and the timer trigger ensures your function executes when that schedule is met.
Configuration
The timer trigger is configured in the function.json
file for your Azure Function. Here's an example:
{
"schedule": "0 */5 * * * *",
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */5 * * * *"
}
]
}
Cron Expression Explained
The schedule
property accepts a cron expression, which consists of six fields:
- Seconds
- Minutes
- Hours
- Day of Month
- Month
- Day of Week
For example, "0 */5 * * * *"
means "run every 5 minutes".
Supported Languages
The timer trigger is supported across all major Azure Functions languages, including:
- C#
- JavaScript
- TypeScript
- Python
- Java
- PowerShell
Example Usage (JavaScript)
Here's a simple JavaScript function triggered by a timer:
module.exports = async function (context, myTimer) {
const timeStamp = new Date().toISOString();
if (myTimer.isPastDue) {
context.log('JavaScript is running late!');
}
context.log('JavaScript timer trigger function ran at:', timeStamp);
};
Best Practices
- Idempotency: Ensure your timer-triggered functions are idempotent, meaning running them multiple times has the same effect as running them once.
- Error Handling: Implement robust error handling and logging to diagnose and resolve issues.
- Monitoring: Utilize Azure Monitor and Application Insights to track the execution of your timer functions.
- Avoid Overlapping: Be mindful of the frequency of your triggers to prevent overlapping executions if your function takes a long time to run.
Advanced Scenarios
Timer Intervals
Instead of a cron expression, you can specify a fixed interval:
{
"schedule": "00:00:05",
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "00:00:05"
}
]
}
This example triggers the function every 5 seconds.
Using Function Timer Context
The timer trigger binding passes a context object to your function, which includes information like isPastDue
. This property is true if the function execution was missed due to being offline or other scheduling conflicts.
Scaling
In a Consumption plan, timer triggers execute on a single instance. For scenarios requiring high throughput or guaranteed execution, consider using a Premium or App Service plan.