A Schedule Task is to perform a number of steps repeatedly once a day or every hour or every minute or in any given sequence as per the requirements. These schedule tasks can be performed automatically by task scheduler. In web applications, also, some routine tasks need to be scheduled.
To develop an efficient system, tasks are grouped together to be executed in background as scheduled tasks.WebJob is to execute a program or script within the context of web app or mobile app or API. WebJob is a feature provided by Azure App service. One can use same service plan for hosting any Web Application and WebJob for executing any long running tasks. WebJobs are of two types – Continuous and Triggered.
Continuous WebJobs are started immediately as WebJobs are created, and are executed in an endless loop. In case an job get stopped, it can be restarted.
Triggered WebJobs are created, but executed only when these WebJobs are triggered.
Create a Triggered WebJob using Azure SDK 3.0
In this sample WebJobs app, I will be using Visual Studio 2017, development account for Azure
WebJobs with a sample connection string provided by Azure for sample apps.
- Create a new project, File>New Project then a dialog for new project will open. In that dialog, traverse C#> Web> .Net Core and Select Console App. A console project will be created
- Add dependencies from nuget package manager for Microsoft.Azure.WebJobs (3.0.3) and Microsoft.Azure.WebJobs.Extensions(3.0.1) as shown in the image below.
- Add a new json file as ‘appsettings.json’ file and add connection string of development account for Azure WebJobs as shown in image below.
- Add WebJobs configuration for Azure WebJobs in main() method of program.cs. The code below will configure all necessary settings for Azure WebJobs.
- In Azure SDK 2.0 an instance of JobHostConfiguration is used to configure settings Like, Tracing and Timer Methods and then this configuration object is passed as a parameter in JobHost instance, JobHost is a runtime container to execute continuous and triggered WebJobs by calling RunAndBlock method of JobHost instance.
- In sdk 3.0 JobHostConfiguration has been removed and in place of it all configurations are configured by HostBuilder.
- The Host Builder is much like the latest ASP.Net Core. Firstly you need to create an instance of HostBuilder and configure it as ‘Development’ environment and then configure WebJobs by calling ConfigureWebJobs method. In this method setup AddAzureStorageCoreServices (it will hook WebJobs to Azure storage Account) and AddTimers ( will let WebJobs to periodically trigger tasks defined in the project).
- Create a TestTimer class and in that class create a method which will get executed every 5 second as shown in the image.
- Run the application and on console, the output will be printed on 5 as you can see in the image below.