1

Can I create an Asp.Net core application that can essentially mimic a windows service and just constantly run in the background? I suspect you can but I am unsure which application type to use (ie. console app, web app, etc.).

Scenario: This is a very niche situation as it will be created for a cloud based environment we are using, Siemens MindSphere. We have an application in the cloud already that can read from a PostgreSQL database, but we need a backend service app which every hour on the hour can call MindSphere Api's, receive data from it and populate a field in the above database with this data. Is this possible using .net core?

Karen Tamrazyan
  • 157
  • 1
  • 11
dsis
  • 103
  • 5
  • *“I am unsure which application type to use (ie. console app, web app, etc.)”* – Note that all ASP.NET Core applications are essentially console applications since they host their own web server. – poke Sep 17 '18 at 12:12

1 Answers1

3

You can use Background tasks. Example of timed task:

internal class TimedHostedService : IHostedService, IDisposable
{
    private readonly ILogger _logger;
    private Timer _timer;

    public TimedHostedService(ILogger<TimedHostedService> logger)
    {
        _logger = logger;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is starting.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero, 
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        _logger.LogInformation("Timed Background Service is working.");
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is stopping.");

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

        return Task.CompletedTask;
    }

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

Registration in Startup.cs in ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddHostedService<TimedHostedService>();
    ...
}
Alex Riabov
  • 6,557
  • 4
  • 32
  • 43
  • Thanks for the reply! Would I implement this in a separate Asp.Net core web application, even though it requires no user interaction? – dsis Sep 17 '18 at 10:31
  • @dsis if you already have an Asp.Net core web application, you can safely add it there. If not, then yes, you'll have to create one, you need to host it somewhere after all – Alex Riabov Sep 17 '18 at 11:01