Keep HangFire application awake on IIS in .NET Core environment

Viewed 1403

I am having difficulties with: IApplicationLifetime CancellationTokens: ApplicationStarted, ApplicationStopped in my .NET core application using HangFire batch application.

The delegates passed to ApplicationStarted.Register() and ApplicationStopped.Register() do not get called. I am using .NET Core version 1.0.

Using below workaround in .NET Core (use appropriate Configuration for your app, inject your own "logger") inside the Startup.Configure(..) method. Note RestartURL:URL is a URL to your application - a lightweight hit.

Current workaround to keep batch process alive:

var batchProcessKeepAliveTimer = new Timer();
        batchProcessKeepAliveTimer.Elapsed += delegate
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(Configuration["Data:RestartURL:URL"]);
            System.Net.WebResponse resp = req.GetResponse();
            logger.Log("Polling batch restart 60 milli second intervals");
        };
        batchProcessKeepAliveTimer.Enabled = true;
        double result = 60000;//default value in milliseconds
        if (Double.TryParse(Configuration["Data:RestartURL:PollingInterval"], out result))
            batchProcessKeepAliveTimer.Interval = result;

Draw backs is: When app pool is manually shut down and restarted, no guarantee that Startup will be called right away. I find that I need to make an explicit HTTP request so that the application pool can re-instantiate the Startup objects. In other words, I need to make a single HTTP call to bootstrap this timer.

However, if the Startup has been instantiated like this, timer can go on for a long time, until it is shut down. Would be less maintenance for your application if the Timer interval is less than IdleTime.

Anybody have a better working approach - especially using .NET core cancellation tokens as above?

0 Answers
Related