简体   繁体   中英

ASP.NET Core run background task on given hours

I want to run a task that performs a database update at the given hours. I'm not sure if this is the correct way, or if is there a way to register this task to run at specific hours that i can parameterize?

    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;
        }

    }

If you would like to use IHostedServices , you could try below code which will run the task at specific hour:

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;
    }

If you would like to pass parameters for BackgroundService, you could also register it using DI,refer to

How to pass parameters for BackgroundService?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM