[英]How to use IHostedService in ASP.Net Core?
I have a class that call REST API.我有一个 class 调用 REST API。 The API return new data every couple minutes.
API 每隔几分钟就会返回新数据。 I want to do background tasks with hosted services so to call the API every 5 minutes.
我想使用托管服务执行后台任务,因此每 5 分钟调用一次 API。 Is the code I have how is suppose to be?
我的代码应该是怎样的? How is this different with BackgroundService?
这与 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)
.虽然我认为你最好调用
_timer.Dispose()
而不是_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此处描述了
BackgroundService
的实现,以及如何使用它的示例: IHostedService with a custom hosting service class 源自 BackgroundService 基础 class
The BackgroundService
class inherits from IHostedService
. BackgroundService
class 继承自IHostedService
。 It just changes your implementation so that all you need to implement is ExecuteAsync()
, instead of both StartAsync()
and StopAsync()
.它只是更改了您的实现,因此您需要实现的只是
ExecuteAsync()
,而不是 StartAsync( StartAsync()
和StopAsync()
。 It just makes your code a little simpler, kind of...它只是让你的代码更简单一点,有点......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.