Timer Trigger Bindings for Azure Functions
The Timer trigger allows you to run a Function periodically. It's ideal for scheduled tasks, background jobs, or synchronizing data.
How It Works
The Timer trigger uses a schedule expression to determine when a function should execute. This expression can be a CRON expression or a delay value. Azure Functions host manages the scheduling and invocation of your timer-triggered functions.
CRON Expressions
CRON expressions provide a powerful way to define complex schedules. They consist of five or six fields, separated by spaces:
- Minute (0-59)
- Hour (0-23)
- Day of the month (1-31)
- Month (1-12)
- Day of the week (0-6, where 0 is Sunday)
- (Optional) Year
Special characters include:
*: Matches any value.,: Specifies a list of values.-: Specifies a range of values./: Specifies interval values (e.g.,*/15in the minute field means every 15 minutes).
CRON Expression Examples:
"0 */5 * * * *": Every 5 minutes."0 0 12 * * MON-FRI": At 12:00 PM every Monday through Friday."0 0 20 1 * *": At 8:00 PM on the 1st of every month."0 0 0 * * *": Every day at midnight.
Configuration
You configure the Timer trigger in your function.json file (for JavaScript, Python, etc.) or by using attributes (for C#).
function.json Example:
{
"scriptFile": "index.js",
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */10 * * * *"
}
]
}
In this example:
name: The name of the timer object that will be passed to your function.type: Must betimerTrigger.direction: Must bein.schedule: The CRON expression defining when the function runs.
C# Attribute Example:
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
public class TimerTriggerFunction
{
private readonly ILogger _logger;
public TimerTriggerFunction(ILogger logger)
{
_logger = logger;
}
[Function("MyTimerFunction")]
public void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer)
{
_logger.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
// Your function logic here
}
}
Examples
JavaScript Example:
index.js
module.exports = async function (context, myTimer) {
const timeStamp = new Date().toISOString();
if (myTimer.isPastDue) {
context.log('JavaScript isPastDue! This means the timer was triggered too late.');
}
context.log('JavaScript timer trigger function executed!', timeStamp);
// Add your scheduled task logic here
};
Python Example:
__init__.py
import datetime
import logging
import azure.functions as func
def main(myTimer: func.TimerRequest) -> None:
utc_timestamp = datetime.datetime.utcnow().isoformat()
if myTimer.past_due:
logging.info('The timer is past due!')
logging.info('Python timer trigger function executed at %s', utc_timestamp)
# Add your scheduled task logic here
Best Practices
- Idempotency: Design your functions to be idempotent, meaning they can be run multiple times without unintended side effects. This is crucial for scheduled tasks that might re-run due to transient errors.
- Error Handling: Implement robust error handling and logging to track any issues with your scheduled executions.
- CRON Expression Testing: Use online CRON expression testers to verify your schedule before deploying.
- Avoid Overlapping Executions: If your task might take longer than the interval between runs, consider implementing logic to prevent concurrent executions or adjust your schedule.
- Monitoring: Leverage Azure Monitor to track function executions, performance, and errors.
Important: Timer triggers are designed for non-distributed scenarios. If you need distributed locking or more advanced scheduling features, consider using Azure Logic Apps or Azure Data Factory.
Tip: For development, you can use a CRON expression like
"0/5 * * * * *" (every 5 seconds) to test your timer function quickly. Remember to change this for production.