asp net core: Global Timer

jurin otruba 41 Reputation points
2022-01-20T08:15:29.07+00:00

I would like to create a global timer which will check some data in the database, for example, once an hour.

So far, I have done this in the Startup.cs file:

    public Startup(IConfiguration configuration)
    {
        Start_GlobalTimer(3600000);
    }


        private void Start_GlobalTimer(double inInterval)
        {
            var t = new System.Timers.Timer();

            t.Elapsed += new ElapsedEventHandler(GlobalTimerWorker);

           t.Interval = inInterval;
           t.AutoReset = true;
           t.Enabled = true;
            t.Start();
        }

        private void GlobalTimerWorker()
        {
             // Here I need access into DBContext and UserManager
        }

My DB context looks like this.

    public class ApplicationDbContext : IdentityDbContext<AppUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor inHttpContextAccessor) :
            base(options)
        {
            m_Options = options;
            m_HttpContextAccessor = inHttpContextAccessor;
        }
......
.....
    }

    public class AppUser : Microsoft.AspNetCore.Identity.IdentityUser
    {
        //--- Members ---
        .........
     }

The Timer works well, but I don't know how to make available ApplicationDbContext and UserManager in timer handler.
I need access to ApplicationDbContext and UserManager in ElapsedEventHandler of Timer.

I am a beginner in asp net core and I need advice. Thank so much.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,199 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,282 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,016 Reputation points Microsoft Vendor
    2022-01-21T05:13:49.317+00:00

    Hi @jurin otruba ,

    You could refer the following sample to create a BackgroundService, then in the BackgroundService, you can access the ApplicationDbContext and UserManager via the IServiceProvider. Code like this:

    using Core5WebApplication.Data; //ApplicationDbContext  
    using Microsoft.AspNetCore.Identity;  
    using Microsoft.EntityFrameworkCore;  
    using Microsoft.Extensions.DependencyInjection;  
    using Microsoft.Extensions.Hosting;  
    using Microsoft.Extensions.Logging;  
    using System;  
    using System.Linq;  
    using System.Threading;  
    using System.Threading.Tasks;  
      
    namespace Core5WebApplication.Services  
    {  
        public class TimedHostedService : IHostedService, IDisposable  
        {  
            private int executionCount = 0;  
            private readonly ILogger<TimedHostedService> _logger;  
            private Timer _timer = null!;  
      
            private readonly IServiceProvider _serviceProvider;  
            public TimedHostedService(ILogger<TimedHostedService> logger, IServiceProvider serviceProvider)  
            {  
                _logger = logger;  
                _serviceProvider = serviceProvider;  
            }  
      
            public Task StartAsync(CancellationToken stoppingToken)  
            {  
                _logger.LogInformation("Timed Hosted Service running.");  
      
                _timer = new Timer(DoWork, null, TimeSpan.FromSeconds(10),  
                    TimeSpan.FromSeconds(10));  
      
                return Task.CompletedTask;  
            }  
      
            private void DoWork(object? state)  
            {  
                var count = Interlocked.Increment(ref executionCount);  
      
                //using ApplicationDbContext.  
                using (IServiceScope scope = _serviceProvider.CreateScope())  
                {  
                    ApplicationDbContext  _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();  
      
                    _logger.LogInformation("First User Name (DBContext): {name}", _context.Users.OrderBy(c=>c.Id).FirstOrDefaultAsync().Result.UserName);   
                }  
                //using UserManger  
                using (IServiceScope scope = _serviceProvider.CreateScope())  
                {  
                    UserManager<IdentityUser> _usermanager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();  
      
                    _logger.LogInformation("First User Name (UserManger): {name}", _usermanager.FindByEmailAsync("aa@hotmail.com").Result?.UserName);  
                }  
                _logger.LogInformation(  
                    "Timed Hosted Service is working. {currentdate} Count: {Count}", DateTime.Now.ToString() ,count);  
            }  
      
            public Task StopAsync(CancellationToken stoppingToken)  
            {  
                _logger.LogInformation("Timed Hosted Service is stopping.");  
      
                _timer?.Change(Timeout.Infinite, 0);  
      
                return Task.CompletedTask;  
            }  
      
            public void Dispose()  
            {  
                _timer?.Dispose();  
            }  
        }  
    }  
    

    Then, register the host service in the Startup.cs file:

            services.AddHostedService<TimedHostedService>();  
    

    After running the application, the result is like this:

    167086-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. AgaveJoe 26,141 Reputation points
    2022-01-20T14:10:27.437+00:00

    See the Hosted Services documentation which has timer and scoped service (for the DB access) examples.

    Background tasks with hosted services in ASP.NET Core

    0 comments No comments

  2. jurin otruba 41 Reputation points
    2022-01-20T17:59:45.807+00:00

    Thanks a lot, I will try

    0 comments No comments

  3. jurin otruba 41 Reputation points
    2022-01-21T06:47:15.763+00:00

    Thank you very much, I already understand how it works

    0 comments No comments