Scheduled WebJob

Sam picture Sam · Dec 1, 2015 · Viewed 10k times · Source

I'm creating a new Azure WebJob project -- which appears to be a polished version of a console app that can run as a web job.

I want this job to run based on a schedule but in the Main() method -- see below -- Microsoft gives you the host.RunAndBlock() for the job to run continuously.

Do I need to change that if I want the job to run at regularly scheduled intervals?

static void Main()
{
    var host = new JobHost();

    // The following code ensures that the WebJob will be running continuously
    host.RunAndBlock();
}

Answer

mathewc picture mathewc · Dec 2, 2015

When using the Azure WebJobs SDK you can use TimerTrigger to declare job functions that run on a schedule. For example here's a function that runs immediately on startup, then every two hours thereafter:

public static void StartupJob(
[TimerTrigger("0 0 */2 * * *", RunOnStartup = true)] TimerInfo timerInfo)
{
    Console.WriteLine("Timer job fired!");
}

You can get TimerTrigger and other extensions by installing the Microsoft.Azure.WebJobs.Extensions nuget package. More information on TimerTrigger and the other extensions in that package and how to use them can be found in the azure-webjobs-sdk-extensions repo. When using the TimerTrigger, be sure to add a call to config.UseTimers() to your startup code to register the extension.

When using the Azure WebJobs SDK, you deploy your code to a Continuous WebJob, with AlwaysOn enabled. You can then add however many scheduled functions you desire in that WebJob.