我想运行一个在给定时间执行数据库更新的任务。我不确定这是否是正确的方法,或者是否可以注册该任务以在可以参数化的特定时间运行?
internal class TimedHostedService : IHostedService
{
private readonly ILogger _logger;
private readonly ProductionContext _context;
public TimedHostedService(ILogger<TimedHostedService> logger, ProductionContext context)
{
_logger = logger;
_context = context;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is starting.");
return Task.CompletedTask;
}
private void DoWork(object state)
{
_logger.LogInformation("Timed Background Service is working.");
if (DateTime.Now.TimeOfDay == new TimeSpan(6, 58, 0) ||
DateTime.Now.TimeOfDay == new TimeSpan(14, 58, 0) ||
DateTime.Now.TimeOfDay == new TimeSpan(22, 58, 0))
{
var registos = _context.Registos.Where(r => r.DataFimTurno.HasValue);
var registosModified = registos;
foreach (var item in registosModified)
{
item.DataFimTurno = DateTime.Now;
}
_context.Entry(registos).CurrentValues.SetValues(registosModified);
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is stopping.");
return Task.CompletedTask;
}
}
答案 0 :(得分:0)
如果您想使用IHostedServices
,则可以尝试以下代码,该代码将在特定时间运行任务:
public Task StartAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
var currentTime = DateTime.UtcNow;
//run background task at 11:00:00
if(currentTime.Hour == 11 && currentTime.Minute == 0 && currentTime.Second == 0)
{
_logger.LogInformation(currentTime.ToString());
DoWork();
}
}
return Task.CompletedTask;
}
如果您想传递BackgroundService的参数,也可以使用DI注册它,请参阅