Search code examples
c#asp.netazure-webjobsazure-webjobssdkazure-webjobs-triggered

Scheduled .NET WebJob V3 example


I've upgraded my .NET (not .NET Core) WebJob from V2 (which was working fine) to V3. I'm having trouble getting it to run. I just want the webjob to call a function I've written according to this CRON schedule: "0 0 8,10,12,14,16,18,20 * * *". The website it's running with is .NET also, not .NET Core.

How do I do this? I just want a simple working .NET code sample. I've seen this question New Azure WebJob Project - JobHostConfiguration/RunAndBlock missing after NuGet updates and this example https://github.com/Azure/azure-webjobs-sdk/blob/00686a5ae3b31ca1c70b477c1ca828e4aa754340/sample/SampleHost/Program.cs and this documentation https://learn.microsoft.com/en-us/azure/app-service/webjobs-sdk-how-to#triggers but none of it is helpful.


Solution

  • Actually the use of .Net webjob or .Net Core webjob are almost same, cause the 3.0 sdk targets .NET standard 2.0. I test with Microsoft.Azure.WebJobs -version 3.0.4 and Microsoft.Azure.WebJobs.Extensions -version 3.0.1, i think your TimerTrigger doesn't work cause you lost call the AddTimers extension methods. You could find the description here:Binding types.

    Other package I use:

    Microsoft.Extensions.Logging -version 2.2.0
    Microsoft.Extensions.Logging.Console -version 2.2.0
    

    This is my main method:

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

    This is my Functions.cs:

    public static void Run([TimerTrigger("0 0 8,10,12,14,16,18,20 * * *")]TimerInfo myTimer, ILogger log)
        {
    
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        }
    

    And use a appsettings.json(Don't forget set the Copy to Output Directory to Copy always) to configure the storage connection string.

    Here is the result:

    enter image description here