首页 > 解决方案 > 使用 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>();

标签: asp.net-coreasp.net-core-2.0asp.net-core-webapi

解决方案


你可以试试

services.AddHostedService<DataRefreshService>;

您也可以尝试使 DataRefreshService 继承自

Microsoft.Extensions.Hosting.BackgroundService

您可以在此处阅读更多相关信息


推荐阅读