Azure | Azure Functions Trigger Types with Use Cases and Examples
Azure Functions support various trigger types to execute code in response to various events. Below are the most common trigger types along with their use cases and C# examples.
1. HttpTrigger
Description
HttpTrigger allows functions to be invoked via HTTP requests.
Use Case
You can create an HTTP Trigger Function to process incoming customer orders. When a client sends an HTTP POST request with order details, the function validates the data, updates a database, and returns a confirmation response.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
public static class ProcessOrderFunction
{
[FunctionName("ProcessOrder")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req)
{
string requestBody = new StreamReader(req.Body).ReadToEnd();
dynamic orderData = JsonConvert.DeserializeObject(requestBody);
if (orderData?.orderId == null || orderData?.product == null)
{
return new BadRequestObjectResult("Invalid order data.");
}
// Simulate processing the order
string responseMessage = $"Order {orderData.orderId} for {orderData.product} has been processed.";
return new OkObjectResult(responseMessage);
}
}
2. TimerTrigger
Description
TimerTrigger allows functions to be executed on a predefined schedule.
Use Case
You can create a TimerTrigger function to run every night at midnight to delete outdated records from a database, archive logs, or remove temporary files from storage
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
namespace TimerTriggerFunctionApp
{
public static class DataCleanupFunction
{
[FunctionName("DataCleanupFunction")]
public static void Run([TimerTrigger("0 0 0 * * *")] TimerInfo myTimer, ILogger log)
{
log.LogInformation($"Timer trigger function executed at: {DateTime.Now}");
// Example: Cleanup logic
try
{
// Simulated cleanup operation
log.LogInformation("Starting data cleanup process...");
// Your cleanup code here, e.g., database operation, file deletion, etc.
log.LogInformation("Data cleanup completed successfully.");
}
catch (Exception ex)
{
log.LogError($"An error occurred during data cleanup: {ex.Message}");
}
}
}
}
3. BlobTrigger
Description
BlobTrigger allows functions to be triggered when new blobs are added to Azure Storage.
Use Case
For instance, you can use it to process uploaded images, such as resizing them for thumbnails or scanning them for content moderation. This functionality eliminates the need for polling and enables real-time processing, enhancing efficiency and automation.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.IO;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
public static class BlobTriggerFunction
{
[FunctionName("BlobTriggerFunction")]
public static void Run(
[BlobTrigger("sample-container/{name}", Connection = "AzureWebJobsStorage")] Stream myBlob,
string name,
ILogger log)
{
log.LogInformation($"BlobTrigger processed blob\n Name: {name} \n Size: {myBlob.Length} Bytes");
}
}
4. QueueTrigger
Description
QueueTrigger allows functions to be triggered when messages are added to Azure Queue Storage.
Use Case
When a customer places an order, the application adds a message containing order details to an Azure Queue. The QueueTrigger function is triggered automatically whenever a new message appears in the queue. The function processes the order, updates the inventory database, and sends a confirmation email to the customer.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
public static class OrderProcessor
{
[FunctionName("OrderProcessor")]
public static void Run(
[QueueTrigger("order-queue", Connection = "AzureWebJobsStorage")] string orderMessage,
ILogger log)
{
log.LogInformation($"Processing order: {orderMessage}");
// Simulate processing the order
try
{
// Example: Deserialize the order message, update database, send confirmation email
log.LogInformation("Order processed successfully.");
}
catch (Exception ex)
{
log.LogError($"Error processing order: {ex.Message}");
}
}
}
5. ServiceBusTrigger
Description
ServiceBusTrigger allows functions to be triggered when messages are sent to Azure Service Bus.
Use Case
Imagine an e-commerce system where orders are placed, and each order is sent as a message to a Service Bus queue. An Azure Function with a ServiceBusTrigger can be used to automatically process these order messages, such as updating the inventory, sending a confirmation email, or logging the order details.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
public class ProcessOrderFunction
{
[FunctionName("ProcessOrder")]
public void Run(
[ServiceBusTrigger("orders-queue", Connection = "ServiceBusConnection")] string message,
ILogger log)
{
log.LogInformation($"Processing order: {message}");
// Add logic to process the order message here.
}
}
6. EventGridTrigger
Description
EventGridTrigger allows functions to be triggered by events from Azure Event Grid.
Use Case
An Azure Event Grid Trigger function can be used to automatically respond to events from services like Azure Blob Storage, such as when a new file is uploaded to a specific container. For instance, you can configure the function to process and log the metadata of uploaded files or initiate downstream workflows.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.EventGrid.Models;
using Newtonsoft.Json.Linq;
public static class EventGridTriggerFunction
{
[FunctionName("HandleEventGridEvent")]
public static async Task Run(
[EventGridTrigger] EventGridEvent eventGridEvent,
ILogger log)
{
log.LogInformation($"Event received: {eventGridEvent.EventType}");
// Parse the data from the event
var data = eventGridEvent.Data as JObject;
log.LogInformation($"Event data: {data?.ToString()}");
// Add additional processing logic here
await Task.CompletedTask;
}
}
7. Durable Functions
Description
Durable Functions enable stateful and orchestrator function patterns, allowing you to define complex workflows in a straightforward manner.
Use Case
Azure Durable Functions can be used in an order processing system to handle complex workflows, such as processing an online order. This involves multiple steps like validating the order, charging the customer, checking inventory, and shipping the product. Each step can be orchestrated reliably, ensuring that failures are retried and that the state of the workflow is preserved.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
public static class OrderProcessingFunction
{
[FunctionName("OrderProcessingOrchestrator")]
public static async Task<List<string>> OrderProcessingOrchestrator(
[OrchestrationTrigger] DurableOrchestrationContext context)
{
var outputs = new List<string>();
outputs.Add(await context.CallActivityAsync<string>("ValidateOrder", null));
outputs.Add(await context.CallActivityAsync<string>("ChargeCustomer", null));
outputs.Add(await context.CallActivityAsync<string>("CheckInventory", null));
outputs.Add(await context.CallActivityAsync<string>("ShipOrder", null));
return outputs;
}
[FunctionName("ValidateOrder")]
public static string ValidateOrder([ActivityTrigger] string input, ILogger log)
{
log.LogInformation("Validating order...");
return "Order Validated";
}
[FunctionName("ChargeCustomer")]
public static string ChargeCustomer([ActivityTrigger] string input, ILogger log)
{
log.LogInformation("Charging customer...");
return "Customer Charged";
}
[FunctionName("CheckInventory")]
public static string CheckInventory([ActivityTrigger] string input, ILogger log)
{
log.LogInformation("Checking inventory...");
return "Inventory Checked";
}
[FunctionName("ShipOrder")]
public static string ShipOrder([ActivityTrigger] string input, ILogger log)
{
log.LogInformation("Shipping order...");
return "Order Shipped";
}
[FunctionName("HttpStart")]
public static async Task<IActionResult> HttpStart(
[HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req,
[DurableClient] IDurableOrchestrationClient starter,
ILogger log)
{
string instanceId = await starter.StartNewAsync("OrderProcessingOrchestrator", null);
log.LogInformation($"Started orchestration with ID = '{instanceId}'.");
return starter.CreateCheckStatusResponse(req, instanceId);
}
}
What next ?
Azure Functions provide a versatile way to trigger code execution in response to various events. By leveraging different trigger types, developers can build a wide range of applications and workflows.