[英]Background task scheduling in .NET CORE
我想根據每個請求創建動態cron作業(如果應用程序服務器關閉,后台任務也不會受到影響),並且cron作業可以重新安排或刪除。在.net core中實現它的最佳方法是什么。
創建一個新的.net核心控制台應用程序並使用以下模板
在您的Program.cs內部主要方法中(C#級別為7):
public static async Task Main(string[] args)
{
var builder = new HostBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
// i needed the input argument for command line, you can use it or simply remove this block
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
Shared.Configuration = config.Build();
})
.ConfigureServices((hostContext, services) =>
{
// dependency injection
services.AddOptions();
// here is the core, where you inject the
services.AddSingleton<Daemon>();
services.AddSingleton<IHostedService, MyService>();
})
.ConfigureLogging((hostingContext, logging) => {
// console logging
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
});
await builder.RunConsoleAsync();
}
這是守護程序/服務代碼
public class MyService: IHostedService, IDisposable
{
private readonly ILogger _logger;
private readonly Daemon _deamon;
public MyService(ILogger<MyService> logger, Daemon daemon /* and probably the rest of dependencies*/)
{
_logger = logger;
_daemon = daemon;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await _deamon.StartAsync(cancellationToken);
}
public async Task StopAsync(CancellationToken cancellationToken)
{
await _deamon.StopAsync(cancellationToken);
}
public void Dispose()
{
_deamon.Dispose();
}
}
這是您想要做的核心,下面的代碼是一個模板,您必須提供正確的實現 :
public class Daemon: IDisposable
{
private ILogger<Daemon> _logger;
protected TaskRunnerBase(ILogger<Daemon> logger)
{
_logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
await MainAction.DoAsync(cancellationToken); // main job
}
}
public async Task StopAsync(CancellationToken cancellationToken)
{
await Task.WhenAny(MainAction, Task.Delay(-1, cancellationToken));
cancellationToken.ThrowIfCancellationRequested();
}
public void Dispose()
{
MainAction.Dispose();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.