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?

4

1 回答 1

3

您可以使用后台任务。定时任务示例:

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();
    }
}

在 Startup.cs 中注册ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddHostedService<TimedHostedService>();
    ...
}
于 2018-09-17T10:06:36.047 回答