ASP.NET CORE开启后台任务
通过Microsoft.Extensions.Hosting.BackgroundService抽象类开启后台任务。/// Copyright(c) .NET Foundation.Licensed under the Apache License, Version 2.0./// <summary>/// Base class for implementing a long runn
·
通过Microsoft.Extensions.Hosting.BackgroundService抽象类开启后台任务。
/// Copyright(c) .NET Foundation.Licensed under the Apache License, Version 2.0.
/// <summary>
/// Base class for implementing a long running <see cref="IHostedService"/>.
/// </summary>
public abstract class BackgroundService : IHostedService, IDisposable
{
protected readonly IServiceScopeFactory _scopeFactory;
private Task _executingTask;
private readonly CancellationTokenSource _stoppingCts =
new CancellationTokenSource();
public BackgroundService(IServiceScopeFactory scopeFactory) {
_scopeFactory = scopeFactory;
}
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
public virtual Task StartAsync(CancellationToken cancellationToken)
{
// Store the task we're executing
_executingTask = ExecuteAsync(_stoppingCts.Token);
// If the task is completed then return it,
// this will bubble cancellation and failure to the caller
if (_executingTask.IsCompleted)
{
return _executingTask;
}
// Otherwise it's running
return Task.CompletedTask;
}
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
// Stop called without start
if (_executingTask == null)
{
return;
}
try
{
// Signal cancellation to the executing method
_stoppingCts.Cancel();
}
finally
{
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite,
cancellationToken));
}
}
public virtual void Dispose()
{
_stoppingCts.Cancel();
}
}
实现:
/// <summary>
/// 实现 BackManagerService 类继承 BackgroundService 抽象类
/// </summary>
public class BackManagerService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Foo();//需要运行的方法
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
}
然后打开 Startup.cs 在 ConfigureServices 方法注入
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHostedService, BackManagerService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献2条内容
所有评论(0)