Search code examples
azureasp.net-coremodel-view-controllerweb-applicationscron

How to use Webjob to call method in WebApp in Azure


I need to call methods every hour in my web app (aspnet core MVC) which is published on Azure. Basically Azure gives opportunity to create webjob in "the context of webapp". How can I use webjob to call methods in webapp. As I understand for webjob I need to create seperate project and then deploy it, but can I link parameters or call methods from webjob?

Also how can access webapp wwwroot with webjob program?


Solution

  • Based on your comment, I would recommend one of two options. The first would be if you just need to update the database, and any logic to do that update can be easily contained within the WebJob itself, then just run the WebJob as a cron process, connect directly to the database in the WebJob, and do the update from there. This is the best option if this DB update doesn't depend on any state or info on the running Web app.

    If you want to actually go through the WebApp, then you notion of creating a route/endpoint on the webapp (protect it in some way!) that calls you necessary method(s) and then have your WebJob use HttpClient to make a web request to that route every hour.

    The code for this second option would be very simple, something like:

    public static async Task UpdateTimer(["0 0 * * * *")] TimerInfo myTimer, ILogger log)
    {
       log.LogInformation($"Timer Invoked: {DateTime.Now}");
       var httpClient = new HttpClient();
       await httpClient.GetAsync("https://my.url.com/special-route");            
    }
    

    Both of these options really don't have to be a WebJob either. They could also be run as a separate Azure Function, which works similar to a WebJob but doesn't actually run within the context of the WebApp and allows it to be managed separately -- if that could be a benefit. Just a thought.