在ASP.NET Core中,可以通过在应用程序的主机中添加一个IHostedService来实现在完成任务之前关闭计划程序。以下是一个示例代码:
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public class ScheduledTask : IHostedService, IDisposable
{
private readonly ILogger _logger;
private Timer _timer;
public ScheduledTask(ILogger logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("ScheduledTask is starting.");
// 设置计划执行任务的时间间隔
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
_logger.LogInformation("ScheduledTask is working.");
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("ScheduledTask is stopping.");
// 停止计划执行任务
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
然后在应用程序的主机中注册ScheduledTask服务:
public class Program
{
public static async Task Main(string[] args)
{
var hostBuilder = new HostBuilder()
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConsole();
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService();
});
await hostBuilder.RunConsoleAsync();
}
}
上述代码中,ScheduledTask
类实现了IHostedService
接口,该接口定义了在应用程序的启动和关闭过程中要执行的任务。在StartAsync
方法中,我们使用Timer
类来设置计划执行任务的时间间隔,并在DoWork
方法中定义实际要执行的任务。在StopAsync
方法中,我们停止计划执行任务。在Dispose
方法中,我们释放Timer
对象。
在应用程序的主机中,我们使用HostBuilder
来构建主机,并通过调用ConfigureServices
方法注册ScheduledTask
服务。然后调用RunConsoleAsync
方法来运行主机。
当应用程序关闭时,StopAsync
方法会被调用,从而停止计划执行任务。