Search code examples
azure-webjobsazure-webjobssdk

Run Azure WebJob on premises server


The application I'm working on has to be deployable on Azure and on a Windows Server.

I'm using a Continuous Azure WebJob, that has some methods with a [TimerTrigger] attribute, that work fine on Azure. But I would like them to trigger also when deployed on premises.

Is this something supported? What would be a recommended way to have the exe with the Azure WebJob SDK running on a Windows Server continuously from a DevOps perspective?

I'm using .NET Core 3 and the Microsoft.Azure.Webjobs 3.0 SDK.


Solution

  • You can consider the web job project as a console project, and just click the your_webjob.exe to run it continuously(by specifying TimerTrigger). And you can follow this article to create a .NET core webjob.

    Here is an example:

    1.Create a .NET core 3.0 console project, and install the following nuget packages:

    Microsoft.Azure.WebJobs.Extensions, version 3.0.0

    Microsoft.Azure.WebJobs.Extensions.Storage, version 3.0.10

    Microsoft.Extensions.Logging.Console, version 3.0.0

    2.Here is the code in program.cs:

    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    
    namespace ConsoleApp2
    {
        class Program
        {
            static void Main(string[] args)
            {
                var builder = new HostBuilder();
                builder.ConfigureWebJobs(b =>
                {
    
                    b.AddTimers();
                    b.AddAzureStorageCoreServices();
                    b.AddAzureStorage();
                });
                builder.ConfigureLogging((context, b) =>
                {
                    b.AddConsole();
                });
    
                var host = builder.Build();
                using (host)
                {
                    host.Run();
                }
            }
        }
    }
    

    3.Add appsettings.json file to the project, and then right click the appsettings.json file -> select properties -> set the "Copy to Output Directory" to "Copy if newer". Here is the appsettings.json:

    {
      "ConnectionStrings": {
        "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=xx;AccountKey=xxx;EndpointSuffix=core.windows.net"
      }
    }
    
    1. Add a Functions.cs to the project. And here is the code in Functions.cs:

      using Microsoft.Azure.WebJobs;
      using Microsoft.Extensions.Logging;
      
      namespace ConsoleApp2
      {
          public class Functions
          {
              public static void CronJob([TimerTrigger("0 */1 * * * *")] TimerInfo timer, ILogger logger)
              {
                  logger.LogInformation("this is a test message!");
              }
          }
      }
      

    5.Build the project, then go to the folder where your_webjob.exe is located, just double click the .exe file, it can run continuously on local:

    enter image description here