简体   繁体   中英

How to use IHostedService in ASP.Net Core?

I have a class that call REST API. The API return new data every couple minutes. I want to do background tasks with hosted services so to call the API every 5 minutes. Is the code I have how is suppose to be? How is this different with BackgroundService?

public class APICaller : IHostedService
{
    private Timer _timer;

    public Task StartAsync(CancellationToken stoppingToken)
    {
        _timer = new Timer(call, null, 0, 300000); //Every 5 minutes

        return Task.CompletedTask;
    }

    private void call(object state)
    {
        var client = new RestClient("https://api.example.com/values/d=A");
        var request = new RestRequest(Method.GET);
        request.AddHeader("accept", "application/json; charset=utf-8");
        IRestResponse response = client.Execute(request);
        var responseContent = response.Content;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }
}

Your code looks good. Although I think you're better off calling _timer.Dispose() rather than _timer?.Change(Timeout.Infinite, 0) . But in the end, it probably won't matter since that's only run when your application is stopping anyway.

The implementation of BackgroundService is described here, along with an example of how to use it: Implementing IHostedService with a custom hosted service class deriving from the BackgroundService base class

The BackgroundService class inherits from IHostedService . It just changes your implementation so that all you need to implement is ExecuteAsync() , instead of both StartAsync() and StopAsync() . It just makes your code a little simpler, kind of...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM