gpt4 book ai didi

c# - 如何在具有不同计时器持续时间的.net核心的后台服务中运行多个任务

转载 作者:行者123 更新时间:2023-12-05 00:56:04 25 4
gpt4 key购买 nike

我正在创建一个工作服务,它将作为 Windows 服务运行。我有一个需求,我想调用两个可能有不同计时器的任务。

DoWork 应该每 5 分钟调用一次,DoAnotherWork 应该每 10 分钟左右调用一次。这两个任务可以并行运行,互不依赖。

我能够创建每 5 分钟运行一次的任务 DoWork。我对如何实现另一个具有不同计时器持续时间的任务感到有些困惑?

public class Worker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private IDataLoaderService _dataLoaderService;

public override Task StartAsync(CancellationToken cancellationToken)
{
using var scope = _scopeFactory.CreateScope();
_dataLoaderService = scope.ServiceProvider.GetRequiredService<IDataLoaderService>();
return base.StartAsync(cancellationToken);
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await DoWork(stoppingToken, _dataLoaderService);
await Task.Delay(300000, stoppingToken); //Run every 5 minutes

await DoAnotherWork(stoppingToken, _dataLoaderService);
await Task.Delay(600000, stoppingToken); //Run every 10 minutes
}
}

private async Task DoWork(CancellationToken stoppingToken, IDataLoaderService loaderService)
{
await loaderService.Process();
}

private async Task DoAnotherWork(CancellationToken stoppingToken, IDataLoaderService loaderService)
{
await loaderService.Validate();
}
}

最佳答案

These two tasks can run in parallel and are not dependant on each other.

听起来你有两个服务:

public class ProcessDataLoaderWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = _scopeFactory.CreateScope();
var dataLoaderService = scope.ServiceProvider.GetRequiredService<IDataLoaderService>();

while (true)
{
await dataLoaderService.Process();
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); //Run every 5 minutes
}
}
}

public class ValidateDataLoaderWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = _scopeFactory.CreateScope();
var dataLoaderService = scope.ServiceProvider.GetRequiredService<IDataLoaderService>();

while (true)
{
await dataLoaderService.Validate();
await Task.Delay(TimeSpan.FromMinutes(10), stoppingToken); //Run every 10 minutes
}
}
}

我还修改了 IDataLoaderService 的使用方式,使其不在其范围之外使用,并将 Task.Delay 参数更改为更加不言自明。

关于c# - 如何在具有不同计时器持续时间的.net核心的后台服务中运行多个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63004613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com