Azure Function Triggers

How To Trigger Azure Functions

This Azure tutorial will discuss Azure Function Triggers and how To Trigger Azure Functions, Azure Function Multiple Triggers, etc.

Azure Function Triggers

Different types of triggers provided by Azure can be used for your Azure Function. Below are the Azure function trigger types.

  • HTTP Trigger: HTTP Trigger is one of the Basic And simple triggers you can use for your Azure Function. In case the HTTP requests come, this trigger gets fired.
  • Queue Trigger: This is another category of trigger you can use for your Azure Function. This trigger gets fired if any new message comes in an Azure Storage queue.
  • TimerTrigger: If you want your Azure Function to execute in a specified time, you can use the Timmer Trigger for your Azure Function.
  • Service Bus Trigger: Service Bust Trigger gets fired if a new message comes from a service bus queue.
  • Azure Event Hub Trigger: Event Hub Trigger gets fired if any events are delivered to the Azure event hub. This trigger is used basically for workflow processing, user experience, etc.
  • Generic Webhook: This is another category of trigger that gets fired for HTTP requests from any service that supports Webhooks.
  • GitHub WebHook: Git Hub Webhook trigger gets fired in case any of the events like Branch created, delete branch, Comment on Commit, etc, occurs in your GitHub repositories.
  • Azure Cosmos DB trigger: This is another type of trigger that gets triggered whenever documents get a change in the Document collection.
  • Azure Event Grip Trigger: This trigger gets triggered whenever the event grid receives a new event.

So, these are the key triggers available for your Azure Function and can be used based on your business needs.

How To Trigger Azure Functions

As we have already discussed, Trigger plays a vital role in the case of Azure Functions. The trigger is the one that invokes the Azure Functions; in other words, the Azure Functions triggers are responsible for starting the Azure Function. You can also trigger Azure function manually.

How To Trigger Azure Function

Note: One Azure function can have only one trigger. An Azure function cannot have more than one trigger.

Create a simple scheduled trigger in Azure Portal

Well, here we will discuss How to create a simple scheduled trigger in the Azure Portal. Suppose you will consider a scenario to display a “Welcome” on the computer screen every 5 minutes. Then, in that case, you can create a timer trigger and set the value for the CORN expression so that the Azure Function will execute at each 5-minute interval.

Follow the below steps for creating a simple scheduled trigger Azure Function in Azure Portal.

Azure Function Timer Trigger

  1. Log in to the Azure Portal (https://portal.azure.com/)
  2. Search for the Function App and click on the search result.
azure functions triggers

3. Now, click on the + Add button to create a function App.

azure function manual trigger

4. On the next window, select your correct Subscription. Choose a Resource group, or if you don’t have any existing Resource group, you can create a new one by clicking the Create new link, Providing a unique name for the Azure Function App, Choosing the code as the Publish option, Choosing the .NET Core as the Runtime stack option, You can choose the version option as 3.1 and finally, choose the region for the Function App and then click on the Next: Hosting > button to go to the Hosting tab.

function app trigger

5. On the Hosting tab, you need to provide an existing storage account; if you don’t have any, you can click the Create a new link to create a new one. If you don’t do anything, it will create a new storage account for you. Now, the next thing is to select the Operating system. The default option is Windows, and choose the plan type. Here, the default option is consumption (serverless).

azure function trigger

Keep the other tab values as it is. Now click on the Review + Create button. Now, it will validate all the values entered and show you the summary Details. Finally, click the Create button to create the Azure Function App in the same window.

Now, you can see it is showing us Your deployment is complete, and you can click on the Go to resource button to navigate to the Function App you have created just now.

how to trigger azure function manually

Now, we will have to add a trigger. To add the trigger, we need to create an Azure Function. Click on the Functions link from the left navigation and then click the + Add button on the Function app page, as highlighted below.

how to run timer trigger azure function manually

On the New Function window, select the template as Timer trigger, as shown below.

azure function app triggers

Provide the name of the Azure timer function, and on the Schedule option, provide the CORN expression as 0*/5****, which means the Azure function will execute on each 5-minute interval of time. Then click on the Create Function button to create the Azure Timmer Function.

azure functions multiple triggers

Now, your Azure Timer function will be created successfully. Click on the Code + Test option from the left navigation. You can able to see the Azure Function code below for the run.csx file

using System;

public static void Run(TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
azure function triggers

Now, you can add the code as per your functionality on this file and then click on the Save button to save the changes. Finally, click the Test/Run button to test the Azure function to see if it works. Now, if we try to run this Azure function to ensure it works fine, click the Test/Run button and then the Run button on the Input window.

Now you can see the logs below that show the execution of the Azure Function on the specified time that is, you can see the Azure trimmer function executed on each 5-minute timeline.

azure function queue trigger example c#

HTTP trigger

As we have already discussed, the HTTP trigger is a simple and very useful trigger used to handle HTTP requests and build the API or services that handle the HTTP requests.

We have already created the Azure Function App. Now, let’s create an HTTP-triggered Azure Function following the below steps. The Purpose of this Azure Function is that When you provide a value for the name parameter, it will validate with a regular expression and show you whether the Output is a valid or invalid name.

Navigate again to the Azure Function App that we have created above. On the Azure Function App page, click on the functions option from the left navigation and then click on the + Add button.

azure function queue trigger example c#

On the new function, select the HTTP trigger Azure function template.

azure function trigger types

In the next window, Provide a name for the HTTP-triggered Azure Function, choose the Authorization level as the function, and then click on the Create Function to create the HTTP-triggered Azure function.

manually trigger azure function

Now, it will create the HTTP-triggered function successfully. Now you can able to see the run.csx file contains the below code

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    string responseMessage = string.IsNullOrEmpty(name)
        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
}

Now replace your Azure Function Code with the code below and click the Save button to save the modified code changes.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Text.RegularExpressions;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    string name = req.Query["name"];
    string pattern = @"^[a-zA-Z-.' ]{2,64}$";

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    bool isNameValid = Regex.IsMatch(name, pattern);      
    log.LogInformation("The result for " + name + ": " + isNameValid);

    return name != null && isNameValid
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("This is not a Valid Name");
}

Now click on the Test/Run button to test the Azure function to see if it is working fine or not. Provide the name value as “@@@@@@@$$$$$” on the Input window and click the Run button.

how to trigger azure function

We got the expected output below with the response code as “400 Bad Request” and the response message as “This is not a valid Name.”

triggers in azure functions

Now we will provide a valid name as “Raj,” and we will run the Azure Function and will see the Output. We got the expected output with the Proper Response Code below.

azure function event hub trigger

Azure Event Hub Trigger

Azure Event Hub trigger provides the option to handle millions of events-based messages. It can help us to process millions of events in a few seconds.

Event Hub Trigger gets fired if any events are delivered to the Azure event hub. The purpose of this trigger is basically for workflow processing, user experience, etc.

Several events will be created by the Event Hubs that can be processed differently. This is used to respond to the event sent to an event hub stream.

Now, let’s create an Azure Event Hub trigger Azure function by following the below steps.

Please navigate to the Azure Function App that we have created above. Click on the functions option from the left navigation on the Azure Function App page and click the + Add button.

Azure Event Hub Trigger Azure Function Example

On the new function, select the Azure Event Hub trigger template.

manually trigger azure timer function

Now, in the next window, Provide a name for the Azure Event Hub trigger and then choose the Event Hub connection as an existing connection or click on the New link to create a new one. Provide the name for the Event Hub name and Event Hub consumer group, then click on the Create Function to create the Azure Event Hub trigger.

azure function types of triggers

Now, you can see the run if you click the Code + Test link.csx file, and below is the code for this file.

#r "Microsoft.Azure.EventHubs"


using System;
using System.Text;
using Microsoft.Azure.EventHubs;

public static async Task Run(EventData[] events, ILogger log)
{
    var exceptions = new List<Exception>();

    foreach (EventData eventData in events)
    {
        try
        {
            string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);

            // Replace these two lines with your processing logic.
            log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
            await Task.Yield();
        }
        catch (Exception e)
        {
            // We need to keep processing the rest of the batch - capture this exception and continue.
            // Also, consider capturing details of the message that failed processing so it can be processed again later.
            exceptions.Add(e);
        }
    }

    // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

    if (exceptions.Count > 1)
        throw new AggregateException(exceptions);

    if (exceptions.Count == 1)
        throw exceptions.Single();
}

Now click on the Test/Run and the Run button on the Input window button to test whether the Azure function is working fine or not.

types of azure function triggers

Azure Function Queue Trigger

Azure Function Queue Trigger is another category of Azure function trigger that gets fired if any new message comes in an Azure storage queue. It delivers asynchronous messages between application components for the communication. It can store a large number of messages and can be accessed with the help of HTTP or HTTPS protocols. The maximum size of a single message is 64 kb.

Let’s see how to create the Azure function queue trigger using the Azure Portal.

Navigate to the Azure Function App you created above, click on the Functions option from the left navigation on the Azure Function App page, and then click on the + Add button to create the new Azure Function Queue trigger.

Azure Function Queue Trigger Azure Function Example

Select the Azure Queue Storage trigger template.

How to create Azure Function Queue Trigger

Provide a name for the function and Queue, select a storage account connection, and click the Create function button.

function app triggers

On the Azure Function page, click the Code + Test link from the left navigation to see the run.csx file.

create Azure Function Queue Trigger C#

The run.csx file contains the below code

using System;

public static void Run(string myQueueItem, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
}

You can modify the run.csx file based on your business requirements.

Now, to check if the function is working fine or not, you can click on the Test/Run button and then click on the Run button on the Input window. Now you can able to see we got the expected response code.

Azure Function Queue Trigger example

Azure Service Bus Trigger

Bus Trigger is responsible for responding to the messages from the service bus queue or topic.

There are two types of Azure Service Bus Triggers are available

  1. Service Bus Queue Trigger: As the name suggests, the Service Bus Queue Trigger works on the first in, first out messages principle. As soon as the message comes from the service bus, the service bus queue trigger gets fired, and then it calls the Azure Function immediately.
  2. Service Bus Topic Trigger: This type of Azure trigger is responsible for scaling to the number of recipients.

Azure Function Multiple Triggers

As per Microsoft, Till now, there is no plan to support multiple triggers per single Azure function. It would be best if you created an Azure function for each requirement. If you think you have some standard code to use, keep the code in a helper method and then call the helper method from each function.

Azure Function HTTP Trigger With Parameters

The Azure Function HTTP Trigger’s main responsibility is invoking the Azure Function with the HTTP Request. HTTP Trigger is one of an Azure Function’s basic and simplest triggers. Mostly, People use the HTTP Trigger while performing the operation with the Azure Function because of its simplicity in the implementation.

You can check out a complete tutorial on Azure Function HTTP Trigger now.

Azure Function Timer Trigger

The Timer trigger sets the execution time or a scheduled execution time of the Azure Function. In another way, a Timer trigger is a trigger that helps you to run a function at a specified time.

You can check out a complete tutorial on Azure Function Timer Trigger now.

Azure Function Queue Trigger

The main responsibility of an Azure FunctionQueue trigger is to get triggered when a new message is entered into the Azure Storage Queue.

When multiple queue messages are waiting, queue storage retrieves a set of messages in a batch and then invokes the function concurrently to process those.

You can check out a complete tutorial on Azure Function Queue Trigger now.

Azure Function Manual Trigger

You can also manually trigger a non-HTTP-triggered function with the help of an HTTP request. In some scenarios, you must trigger an Azure Function at a scheduled time. Timmer trigger is one of the examples here.

You can use tools like PostMan, Fiddler, cURL, etc, to send the HTTP requests.

You can check out a simple example of an Azure Function Timmer Trigger now.

Get the _master key of Azure Function.

Part of the functionality to execute a non-HTTP triggered Azure function is to retrieve the _master key of the Azure Function App. To get the _master key of the Azure Function App, follow the steps below.

  • Log in to the Azure Portal (https://portal.azure.com/).
  • Navigate to the Azure Function App.
  • On the Function App page, click the App keys from the left navigation and then click on _master as highlighted below.
http trigger azure function example c#
  • Click the copy to clipboard button on the Edit host key window to copy the _master key value. Keep this key value in a notepad, as we will use the same in the next part of our implementation. Click on the OK button.
types of triggers in azure functions

Now, navigate to the Azure function, click on the Code + Test button from the left navigation, and then click the Test/Run on the Azure Function page. Now click on the Run button on the Input window. You can see below that we got the output as 202 Accepted.

manually trigger timer function azure

Calling the Azure Function

Let’s open the Postman app and enter the below details

  1. Enter the Azure function URL text box in the URL text box. The URL will be (https://demofunctionapp36.azurewebsites.net/admin/functions/QueueTrigger1). Where QueueTrigger1 is the name of the Azure function, admin/functions is the folder path, and https://demofunctionapp36.azurewebsites.net/ is the Azure Function app global URL or location.
  2. Choose the HTTP method as POST.
  3. Select the Headers tab.
  4. Type x-functions-key as the first key and paste the _master key as the value you copied above.
  5. Type Content-Type as the second key and the value as application/json as mentioned below.
azure functions trigger types

6. Select the Body tab and Type { “input”: “test” } as the body for the request, as shown below.

azure trigger function

7. once you click the send button, you can see the expected output as Status: 202 Accepted.

azure function timer trigger run manually

You may also like following the articles below.

Wrapping Up

Well, in this article, we have discussed Azure Function Triggers and How To Trigger Azure Functions, and we have also discussed Azure Function Multiple Triggers. I hope you have enjoyed this article !!!