Azure Functions Timer Trigger

The Timer trigger allows you to run an Azure Function on a schedule. This is useful for scenarios like running a scheduled cleanup task, sending out daily reports, or synchronizing data at regular intervals.

How it Works

The Timer trigger uses a CRON expression or a TimeSpan to define the schedule. When the scheduled time arrives, the trigger activates your function. You can configure the trigger to run at specific times, recurring intervals, or even at a fixed rate.

Key Concepts

CRON Expressions Explained

A CRON expression consists of six fields (in order):

  1. Minute (0-59)
  2. Hour (0-23)
  3. Day of the month (1-31)
  4. Month (1-12)
  5. Day of the week (0-6, where 0 is Sunday)
  6. Year (optional, can be a specific year or * for any year)

Special characters include:

Example CRON Expressions:

CRON Expression Description
0 * * * * * Every hour at minute 0.
0 0 * * * * Every day at midnight.
0 0 12 * * * Every day at 12:00 PM.
0 30 * * * * Every hour at 30 minutes past the hour.
0 0 8 1 * * On the first day of every month at 8:00 AM.
0 0 * * 1 * Every Monday at midnight.

Using TimeSpan

You can also use a TimeSpan for simpler, fixed-interval schedules. For example, to run a function every 5 minutes:

"00:05:00"

Configuration

The timer trigger is typically configured in the function.json file (for JavaScript, Python, and other languages) or via attributes (for C#).

function.json Example (JavaScript/Python)


{
  "scriptFile": "../run.js",
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 */5 * * * *" // Every 5 minutes
    }
  ]
}
        

C# Example (using Attributes)


using Microsoft.Azure.WebJobs;

public static class TimerTriggerCSharp
{
    [FunctionName("TimerTriggerCSharp")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer)
    {
        // Your function logic here
    }
}
        

Tip: For development, you can set the schedule to run more frequently, like every minute or even every few seconds, to test your timer-based logic. Remember to adjust it back to your desired schedule for production.

Handling Missed Executions (IsPastDue)

The IsPastDue property is crucial for understanding if your function execution was delayed. If IsPastDue is true, it means the timer should have fired earlier but couldn't due to system issues or the function taking longer than expected to complete.

It's important to design your functions to be idempotent if they are susceptible to running multiple times due to missed executions. This means that running the function multiple times should produce the same result as running it once.

Common Use Cases

Best Practices