2021-09-01

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("测试结束任务");
        }
    }
  1. 配置服务中心注入该方法就可以了,即在Startup.cs中注入
 //后台任务服务
     services.AddHostedService<TimerTaskService>();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值