asp.net-core - 使用 iHostedService 运行多个后端服务
问题描述
目前,我的 Web API 能够按计划运行并触发另一个端点以同步数据。需要调用的服务存储在一个 yml 文件中。我已经设法让它为一项服务运行计划。我想要的是能够使用自己的时间表保存多个端点,并在正确的时间安排和执行它们。
这是我现在拥有的代码
我已经使用 iHostedService 接口完成了这项工作。
这是实现 iHostedService 的 HostService 类
public abstract class HostedService : IHostedService
{
private Task _executingTask;
private CancellationTokenSource _cts;
public Task StartAsync(CancellationToken cancellationToken)
{
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_executingTask = ExecuteAsync(_cts.Token);
// If the task is completed then return it, otherwise it's running
return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
// Stop called without start
if (_executingTask == null)
{
return;
}
// Signal cancel
_cts.Cancel();
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken));
cancellationToken.ThrowIfCancellationRequested();
}
// cancel
protected abstract Task ExecuteAsync(CancellationToken cancellationToken);
}
ExecuteAsync
然后我扩展这个类并实现如下需要做的事情
public class DataRefreshService : HostedService
{
private readonly DataFetchService _dataFetchService;
public DataRefreshService(DataFetchService randomStringProvider)
{
_dataFetchService = randomStringProvider;
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
try
{
while (!cancellationToken.IsCancellationRequested)
{
await _dataFetchService.UpdateData(cancellationToken);
TimeSpan span = _dataFetchService.GetNextTrigger();
await Task.Delay(span, cancellationToken);
}
} catch (Exception)
{
await StopAsync(cancellationToken);
throw new Exception("Error trigger Sync service");
}
}
}
这是我添加到 Startup.cs 文件中的内容
services.AddSingleton<DataFetchService>();
services.AddSingleton<IHostedService, DataRefreshService>();
解决方案
你可以试试
services.AddHostedService<DataRefreshService>;
您也可以尝试使 DataRefreshService 继承自
Microsoft.Extensions.Hosting.BackgroundService
您可以在此处阅读更多相关信息
推荐阅读
- mongodb - 在 mongoDB 的分组聚合中解析 JSON 内容
- python - 将 MySQL 套接字与 Orange3 一起使用
- html - Vuetify 嵌套数据表列的宽度问题
- node.js - 使用 opentype.js 创建字体子集得到“OTS 解析错误:cmap:解析表失败”错误
- javascript - KonvaJS:分离后如何保持形状在组中的位置和旋转?
- spring-integration - if...else 和 spring 集成中的循环
- php - 用于通过网站从包含服务器上指定文件夹中的文件的列表页面下载文件的 PHP 脚本
- apache-spark - 更新 Pyspark Dataframe 中的多个列
- iis - 八达通如何检查IIS是否重置
- linkage - GnuCobol 相当于 NOSSRANGE