Search code examples
asp.netazureazure-functionsbackground-service

How to implement infinitely running background tasks in ASP.NET without third party services and without Windows Service?


Background

I am not experienced in .NET, ASP.NET, Blazor or Azure. However, I would like to give it a try by building a simple web app with a specific functionality.

I have some experience with Elixir and the Phoenix framework. In Elixir (and Phoenix) it is quite common to have indefinitely running background tasks which are executed independently from the typical user->server request path. They are safe to run for long periods of time. A typical Elixir Phoenix [gen]server can call itself making an infinite loop.

Objective

I would like to know if it would be possible to build an ASP.NET server application which can run potentially infinitely running background tasks which are independent of any user requests. These tasks could be also called "scheduled" tasks, but I instead of saying "run this task every X minutes" I would rather prefer to say "keep running this task again and again while the server application is running".

It would be nice to avoid any dependence on third-party services that abstract the scheduling. Also, it would be nice to be able to deploy such an application on Linux, which means it cannot rely on Windows Service functionality.

What I have checked

I have read that BackgroundService can be used to implement a background/scheduling functionality, but some developers say it might be cumbersome. It looks like there can be third-party libraries and services for that, including scheduled Azure functions, but I would like to know if ASP.NET allows to implement such a functionality "in-house" and run it on one's (Linux) server.


Solution

  • I think that the options you already have checked, e.g. use the BackgroundService from here or use the Azure variant of a TimerTrigger running on a CRON-schedule is not so bad at all. Why invent the wheel again if Microsoft or other (renowned) parties already did the work for you / us? :)

    Also, (correct me if I'm wrong) if you use the latest and greatest version of ASP.NET Core it can be run on a Linux server, e.g. via NGINX or APACHE

    Some example from the "Timed Background Task docs":

    public class TimedHostedService : IHostedService, IDisposable
    {
        private int executionCount = 0;
        private readonly ILogger<TimedHostedService> _logger;
        private Timer? _timer = null;
    
        public TimedHostedService(ILogger<TimedHostedService> logger)
        {
            _logger = logger;
        }
    
        public Task StartAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Timed Hosted Service running.");
    
            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(5));
    
            return Task.CompletedTask;
        }
    
        private void DoWork(object? state)
        {
            var count = Interlocked.Increment(ref executionCount);
    
            _logger.LogInformation(
                "Timed Hosted Service is working. Count: {Count}", count);
        }
    
        public Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Timed Hosted Service is stopping.");
    
            _timer?.Change(Timeout.Infinite, 0);
    
            return Task.CompletedTask;
        }
    
        public void Dispose()
        {
            _timer?.Dispose();
        }
    }