How to work with Azure WebJobs in C#

Take advantage of Azure WebJobs to run scheduled background tasks in the Microsoft Azure cloud

How to work with Azure WebJobs in C#
Thinkstock

Azure WebJobs give you an easy way to schedule and execute background tasks in Microsoft Azure. The Azure WebJobs SDK simplifies the work of creating background tasks with declarative binding and trigger management features. Your Azure WebJobs then can be executed in three different ways: They can run continuously, or on a pre-defined schedule, or even on demand. In this article we will examine how we can build and deploy Azure WebJobs in .Net.

First off, you should make sure that you have Visual Studio 2017 and all of the latest updates installed. You will also need the Azure SDKs including the Azure Functions and Web Jobs Tools. You can install the Azure development tools in Visual Studio by choosing Tools -> Get Tools and Features. And you can ensure you have the latest updates to the Azure Functions and Web Jobs Tools by choosing Tools -> Extensions and Updates. 

Create an Azure WebJob project in Visual Studio

Assuming that you have Visual Studio and the Azure Functions and Web Jobs Tools installed in your system, you can follow these steps to create a new Azure WebJob project in Visual Studio.

  1. Open Visual Studio IDE
  2. Click File -> New -> Project
  3. In the New Project Dialog Window, select the Cloud group
  4. Select Azure WebJob from the list of the project templates
  5. Specify the name and location for your project and click OK to save

This will create a WebJob project in Visual Studio. Next, right-click the project in the Solution Explorer window, select “Manage NuGet Packages for Solution,” and install the updates for the following NuGet packages via the NuGet Package Manager.

  • Microsoft.Azure.KeyValue.Core
  • Microsoft.Azure.WebJobs
  • Microsoft.Azure.WebJobs.Core
  • Microsoft.Azure.WebJobs.Extensions

Build a simple Azure WebJob in .Net

Since Azure WebJob projects are similar to console applications, your project will have a Program.cs file by default. This Program.cs file will contain a Main method—the entry point of the program. Here is where you can specify the configuration metadata for your WebJob.

Let’s take a look at the Main function in the Program.cs file. The default version of Main looks like this:

static void Main()
        {
            var config = new JobHostConfiguration();
            if (config.IsDevelopment)
            {
                config.UseDevelopmentSettings();
            }
            var host = new JobHost(config);
            host.RunAndBlock();
        }

We will edit this default version to create our own Main. The following code snippet illustrates how you can create an instance of JobHostConfiguration and configure the properties of the WebJob.

static void Main()
        {
            var config = new JobHostConfiguration();
            config.UseTimers();
            config.Queues.MaxDequeueCount = 2;
            config.Queues.MaxPollingInterval =
            TimeSpan.FromSeconds(10);
            config.Queues.BatchSize = 10;
            var host = new JobHost(config);
            host.RunAndBlock();
        }

In our new version of Main, the UseTimers() method is called on the config object so that we can leverage timers in the functions we will use. Note the usage of the MaxDequeueCount and MaxPollingInterval properties of the Queues collection, which pertains to the instance of the JobHostConfiguration class. MaxDequeueCount is used to specify the number of times the function will attempt to process a particular message if there is an error. (The default value of this property is 5.) MaxPollingInterval is used to specify maximum polling interval, i.e., the maximum amount of time the WebJob will wait between checks of the queue.

There is another important property worth discussing here. The BatchSize property is used to specify the number of items that the WebJob will process as part of a batch. Here we have specified a BatchSize of 10. Hence, if there are 10 or more items in the queue, no more than 10 would be processed in parallel.

Writing functions for Azure WebJobs

In the WebJob project that you have created, you’ll have a file called Functions.cs that contains a class named Functions. Here is how this class will look initially.

public class Functions
    {
        public static void ProcessQueueMessage([QueueTrigger(“queue”)] string message, TextWriter log)
        {
            log.WriteLine(message);
        }
    }

You will not need to invoke the functions you write here, as they will be called automatically based on the trigger defined. There are three types of trigger, namely QueueTrigger, ErrorTrigger, and TimerTrigger.

Here is a simple QueueTrigger for your reference.

public static void ProcessQueueMessage([QueueTrigger(“idgmessage”)] string message, TextWriter log)
        {
            log.WriteLine(“This will execute when there is a message in the queue”);
            log.WriteLine(message);
        }

And here is a simple example of a TimerTrigger.

public static void ProcessQueueBasedOnTimer([TimerTrigger(“*/5 * * * * *”)] TimerInfo timer)
        {
            Console.WriteLine(“This should execute based on a schedule”);
        }
The TimeTrigger shown here would be invoked periodically based on the cron expression specified. The cron expression “*/5 * * * * *” indicates that the trigger will be fired every five seconds. 

Deploying your Azure WebJob

Once you have created your WebJob and the functions that it should execute, it’s time for you to publish it to Azure. To do this, simply right-click the project in the Solution Explorer Window and select “Publish As Azure WebJob.” Note that you should have an Azure Web App available to host your WebJob. You can just select the publish target as “Import” and then import the publishing profile. Alternatively, you can select the publishing target as “Microsoft Azure App Service” and follow the steps.

When developing applications, we will often want to execute related tasks automatically at pre-defined time intervals. Azure WebJobs provide a nice and simple way to run scheduled jobs in the background in the Microsoft Azure cloud.

Copyright © 2018 IDG Communications, Inc.

How to choose a low-code development platform