.NET Core 2.0 引入了 IHostedService ,基於它可以很方便地執行后台任務,.NET Core 2.1 則錦上添花地提供了 IHostedService 的默認實現基類 BackgroundService ,在這篇隨筆中分別用 Web 與 Console 程序體驗一下。
首先繼承 BackgroundService 實現一個 TimedBackgroundService
public class TimedBackgroundService : BackgroundService
{
private readonly ILogger _logger;
private Timer _timer;
public TimedBackgroundService(ILogger<TimedBackgroundService> logger)
{
_logger = logger;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
_logger.LogInformation($"Hello World! - {DateTime.Now}");
}
public override void Dispose()
{
base.Dispose();
_timer?.Dispose();
}
}
在 ASP.NET Core Web 程序中執行這個后台定時任務只需在 Startup 的 ConfigureServices 注冊 TimedBackgroundService 即可:
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<TimedBackgroundService>();
}
然后只要站點啟動,就會定時輸出日志:
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
Hello World! - 9/14/2018 17:48:02
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
Hello World! - 9/14/2018 17:48:07
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
Hello World! - 9/14/2018 17:48:12
接下來在控制台程序中體驗一下。
基於 Generic Host 實現如下的控制台程序,也是執行在 ConfigureServices 中注冊一下 TimedBackgroundService 。
class Program
{
public static async Task Main(string[] args)
{
var builder = new HostBuilder()
.ConfigureLogging(logging =>
{
logging.AddConsole();
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<TimedBackgroundService>();
});
await builder.RunConsoleAsync();
}
}
dotnet run 運行程序后 TimedBackgroundService 定時輸出了日志:
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
Hello World! - 9/14/2018 17:59:37
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
Hello World! - 9/14/2018 17:59:42
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
Hello World! - 9/14/2018 17:59:47
體驗完成。