我希望根据每个请求创建一个动态的cron作业(如果应用服务器关机,不应该影响后台任务),并且可以重新安排或删除cron作业。如何在.NET核心中实现这一点?
发布于 2018-12-03 14:27:49
创建一个新的.NET核心控制台应用程序,并在主方法(使用C# 7)内的Program.cs中使用以下模板:
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();
}
}https://stackoverflow.com/questions/53593113
复制相似问题