0

I have a web application, asp.net core. It is hosted at a third party hosting service so I have little control over the IIS settings (app pool, etc.). In fact, I only have one app pool in my contract.

I need to add timed services to the app so it will wake up every hour or so, check things and send emails when needed. It would seem that if I use the timer, that when the app pool recycles, the timer wouldn't restart. So it would require someone to access the site to get things running again.

I could write a service to ping the site periodically to keep it alive but am wondering if there would be a better way. Since I am running in a hosted environment I have very limited (or no) access to the server itself.

What would be the best way to handle this?

Jason Pan
  • 15,263
  • 1
  • 14
  • 29

1 Answers1

0

In ASP.NET Core, background tasks can be implemented as hosted services.

Background tasks with hosted services in ASP.NET Core

Here is the blog about how to Run and manage periodic background tasks in ASP.NET Core 6 with C#

Test Result

enter image description here

Sample Code

I am using asp.net core signalr and send the message to all clients.

using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SignalRMiddleawre.Hubs;

namespace BackgroundService
{
    public class TimedHostedService : IHostedService, IDisposable
    {
        private int executionCount = 0;
        private readonly ILogger<TimedHostedService> _logger;
        private readonly IHubContext<MainHub> _hubcontext;
        private Timer? _timer = null;

        public TimedHostedService(IHubContext<MainHub> hubcontext, ILogger<TimedHostedService> logger)
        {
            _hubcontext = hubcontext;
            _logger = logger;
        }

        public  Task StartAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Timed Hosted Service running.");
            _hubcontext.Clients.All.SendAsync("Chat_ReceiveMessage", "[System - Background Service ]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + "Timed Hosted Service running.");
            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(3));

            return Task.CompletedTask;
        }

        private void DoWork(object? state)
        {
            var count = Interlocked.Increment(ref executionCount);

            _logger.LogInformation(
                "Timed Hosted Service is working. Count: {Count}", count);
            _hubcontext.Clients.All.SendAsync("Chat_ReceiveMessage", "[System - Background Service ]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + "DoSomethingAsync method triggered.  Count: "+count+"");
        }

        public  Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Timed Hosted Service is stopping.");
             _hubcontext.Clients.All.SendAsync("Chat_ReceiveMessage", "[System - Background Service ]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + "Timed Hosted Service is stopping.");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
}

Register it in Program.cs file.

enter image description here

Jason Pan
  • 15,263
  • 1
  • 14
  • 29