How To Create Azure WebJob

In this article we will learn about how to create Azure web jobs, it is a great way to run scheduled tasks or handle events using storage queues and custom Cron expression.

  1. Create a new Azure web job project.

2. Add Microsoft.Azure.WebJobs.Extensions nugget package and install.

3. In your app.config you will find the two connection strings where you will add your storage key.

<connectionStrings>
    <add name="AzureWebJobsDashboard" connectionString="" />
    <add name="AzureWebJobsStorage" connectionString="" />
</connectionStrings>

4. Put the below code in the program.cs

static void Main()
{
    var config = new JobHostConfiguration();

    if (config.IsDevelopment)
    {
        config.UseDevelopmentSettings();
    }
    config.UseTimers();
    config.Queues.MaxDequeueCount = 2;
    config.Queues.MaxPollingInterval = TimeSpan.FromSeconds(10);
    config.Queues.BatchSize = 2;

    var host = new JobHost(config);
    host.RunAndBlock();
}
  • UseTimers();The UserTimers allows us to use a timer trigger in our functions.
  • Queues.MaxDequeueCount = 2;The MaxDequeueCount is the number of times your function will try to process a message if its errors occur.
  • Queues.MaxPollingInterval = TimeSpan.FromSeconds(10);MaxPollingInterval is the max number of times the WebJob will check the queue values.
  • Queues.BatchSize = 2; 

    The BatchSize property is the number of items your WebJob will process at the same time.

  • RunAndBlock();The RunAndBlock ensures that the WebJob will be running continuously.

5. Put below function in functions.cs file.

public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log)
{
    log.WriteLine(message);
}
  • This function will get triggered/executed when a new message is written/Added on an Azure Queue called a queue.
public static void TwoMinutesTask([TimerTrigger("0 */2 * * * *", RunOnStartup = true)] TimerInfo timer)
{
    Console.WriteLine("This should run every 2 minutes");
}
  • The simplest way to use the TimerTrigger is to use a Cron expression to define the scheduling for the function. You can also set up custom schedules.

 

I hope this article helps you 🙂

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories