1. 程式人生 > 其它 >netcore 後臺任務 指定每天某一時間執行任務

netcore 後臺任務 指定每天某一時間執行任務

簡單的實現每天執行一次的定時器,執行時間放在資料庫為了使用者能方便隨意修改。

實現方式,通過backgroundService後臺任務,放入每1小時檢視資料庫中的時間一次,如果執行時間正好在1小時之內,就使用System.Threading.Timer執行一次任務。

1、在Startup.cs註冊兩個服務

  services.AddScoped<AutoSubmitApplicationService>();           

services.AddHostedService<BackgroundApplySubmitService>();

2、BackgroundApplySubmitService

 public class BackgroundApplySubmitService : BackgroundService
    {
        private readonly ILogger<BackgroundApplySubmitService> _logger;
        private readonly AutoSubmitApplicationService _applictionService;
        private Timer _timer;

        public BackgroundApplySubmitService(ILogger
<BackgroundApplySubmitService> logger, IServiceScopeFactory factory) { _logger = logger; _applictionService = factory.CreateScope().ServiceProvider.GetRequiredService<AutoSubmitApplicationService>(); ; } protected override Task ExecuteAsync(CancellationToken stoppingToken) {
_timer = new Timer(_applictionService.GetTimeOfApplictionSubmit, null, 10000,3600000); return Task.CompletedTask; } public override void Dispose() { base.Dispose(); _timer?.Dispose(); } }

3、AutoSubmitApplicationService

 public class AutoSubmitApplicationService
    {
        private readonly DataContext db;
        private readonly ILogger<AutoSubmitApplicationService> _logger;
        public AutoSubmitApplicationService(DataContext dbContext, ILogger<AutoSubmitApplicationService> logger)
        {
            _logger = logger;
            db = dbContext;
        }

        public void GetTimeOfApplictionSubmit(object o)
        {
            var item = db.SetAutoApplication.FirstOrDefault();
            var isStartUp = item?.IsStartUp ?? false;
            var gotoTime = item?.GotoTime ?? "";

            if (isStartUp &&  Regex.IsMatch(gotoTime, @"^\d{2}:\d{2}$")) 
            {
                var arrtime = gotoTime.Split(":").Select(x => Convert.ToDouble(x)).ToArray();
                var h = arrtime[0];
                var m = arrtime[1];
                DateTime oneOClick = DateTime.Today.AddHours(h).AddMinutes(m);
                DateTime now = DateTime.Now;
                Console.WriteLine(oneOClick+":::"+now);
                var due = (int)((oneOClick - now).TotalMilliseconds);
                Console.WriteLine(due);
                if ((due >= 0 && due <= 3600000))
                {
                    //在一個小時內執行任務
                    var task = new System.Threading.Timer(DoWord);
                    task.Change(due, 0);
                }
            }
        }

        private void DoWord(object o)
        {
            Console.WriteLine("一天只執行一次");
        }

    }

實現完畢