net.core 定时任务
1.使用 BackgroundService,利用后台服务在后台推送了长时间运行的任务。我们继承BackgroundService之后需要重写ExecuteAsync抽象方法,然后我们只需要在ExecuteAsync方法中写入自己需要执行的方法就可以了
2._jobService 接口里是 定时的具体任务。以构造函数的方式注入。
3._timer 这是一个计时器
具体代码如下:
public class TimerTaskService : BackgroundService
{
private readonly ILogger<TimerTaskService> _logger;
public readonly IJobRepository _jobService;
private Timer _timer;
public TimerTaskService(ILogger<TimerTaskService> logger, IServiceProvider services)
{
Services = services;
_logger = logger;
}
public IServiceProvider Services { get; }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("测试定时任务开始");
#region Timer
//获取执行时间
DateTime ExecuteTime = DateTime.Today.AddHours(14);
//如果已经过了执行时间,明天上午同一时间
if (DateTime.Now > ExecuteTime)
ExecuteTime = ExecuteTime.AddDays(1);
int timeToFirstExecution = (int)ExecuteTime.Subtract(DateTime.Now).TotalMilliseconds;
int timeBetweenCalls = (int)new TimeSpan(24, 0, 0).TotalMilliseconds;
//计时器将执行。之后,它将每24小时执行一次。
_timer = new System.Threading.Timer(DoWork, null, timeToFirstExecution, timeBetweenCalls);
#endregion
_logger.LogInformation("测试定时任务结束");
await Task.Delay(10000, stoppingToken);
}
private void DoWork(object state)
{
_logger.LogInformation("测试开始任务");
using (var scope = Services.CreateScope())
{
var scopedProcessingService =
scope.ServiceProvider
.GetRequiredService<IJobRepository>();
scopedProcessingService.GetXXInfo();
}
_logger.LogInformation("测试结束任务");
}
}
- 配置服务中心注入该方法就可以了,即在Startup.cs中注入
//后台任务服务
services.AddHostedService<TimerTaskService>();