This tutorial guides you through creating and configuring an Azure Function that runs on a schedule using the Timer trigger.
The Timer trigger allows you to run code on a defined schedule. It's ideal for tasks like:
Before you begin, ensure you have the following:
Open your terminal or command prompt and run the following commands:
bashfunc init MyTimerFunctionApp --worker-runtime csharp --docker
Replace csharp with your preferred runtime (e.g., node, python, powershell).
Navigate into the newly created directory:
bashcd MyTimerFunctionApp
Run the following command to create a new function with a Timer trigger:
bashfunc new --name MyTimerTrigger --template "Timer trigger"
This command creates a new folder named MyTimerTrigger containing your function files.
The Timer trigger's schedule is defined in the function.json file within your trigger's folder. Open MyTimerTrigger/function.json.
json{
"scriptFile": "__init__.py",
"bindings": [
{
"name": "mytimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */5 * * * *"
}
]
}
The schedule property uses a CRON expression. In the example above, "0 */5 * * * *" means the function will run every 5 minutes.
0 0 * * * *: Every hour at the start of the hour.0 0 12 * * MON-FRI: Every weekday at 12:00 PM.*/10 * * * * *: Every 10 seconds (for testing, not recommended for production).The actual code for your timer function depends on your chosen runtime.
Open MyTimerTrigger/__init__.py and modify it as follows:
pythonimport 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)
Open MyTimerTrigger.cs (or similar) and modify it.
csharpusing System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace MyTimerFunctionApp
{
public static class MyTimerTrigger
{
[FunctionName("MyTimerTrigger")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.UtcNow}");
if (myTimer.IsPastDue)
{
log.LogInformation("C# Timer trigger function is running late!");
}
}
}
}
IsPastDue property in your code to detect if the function missed a scheduled run.
From the root of your project directory (MyTimerFunctionApp), run:
bashfunc start
Your function app will start, and the timer trigger will begin executing according to its schedule.
Once you are satisfied with your function, you can deploy it to Azure.
bashfunc azure functionapp publish <YourFunctionAppName>
This tutorial provided a basic introduction to creating an Azure Functions Timer Trigger. You can extend this by integrating with other Azure services or implementing more complex logic.