Joydip Kanjilal
Contributor

How to work with Azure WebJobs in C#

how-to
Jul 02, 20185 mins
C#Cloud ComputingMicrosoft Azure

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

cloud enterprise
Credit: 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.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author