简体   繁体   中英

Add timer method to asp.net core 3.1 startup

I want to set a Timer to a method, so its called every, say, 10 minutes, while the application is running.

I have read up on it, but I haven't found an example, where it seems to have the same configuration/start up settings and the time tutorials mostly work with a main method, so I haven't figured out yet, which services I have to add to my startup and/or where to put my time and method.

So I would set my timer like here :

var stateTimer = new Timer(MyMethod, null, 1000, 600000); //any way to change miliseconds to minutes here?

and then write my method like:

static void MyMethod
{
 //all the code I want to execute every 10 minutes
}

This is my Startup:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

       
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            //....

        }

        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //...        
        }
    }
}

So where do I put the time and the method? If someone has an example using the same structure of startup, etc. it would be greatly appreciated. I have found for example this , but it's different from my setup.

I would put your timer into a IHostedService . Microsoft provides some documentation on how to do that exactly.

Using thread might be helpful but i am not sure does it work properly on web app.

Call CallingMyMethodEveryTenSecond() this method inside ConfigureServices

    // This method gets called by the runtime. Use this method to add 
    //services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
       CallingMyMethodEveryTenSecond();
    }

Example console app

Refrence: Calling a method every x minutes

Output:

在此处输入图像描述

Code:

class Program 
{
    static void Main(string[] args)
    {
        //After call this method, it will run every 10 second.
        //Mean time you can call other methods or do other things, 
        //it will still run every 10 second
        CallingMyMethodEveryTenSecond();
        while (true)
        {
            DoSomething();
        }
    }

    private static void CallingMyMethodEveryTenSecond()
    {
        var startTimeSpan = TimeSpan.Zero;
        var periodTimeSpan = TimeSpan.FromSeconds(10);

        var timer = new System.Threading.Timer((e) =>
        {
            MyMethod();
        }, null, startTimeSpan, periodTimeSpan);
    }

    private static void MyMethod()
    {
        Console.WriteLine("may i interrupt you each 10 second ?");
    }
    
    private static void DoSomething()
    {
        Console.WriteLine("Doing something");
        System.Threading.Thread.Sleep(1000);
    }
}

I've used Quartz.NET job scheduler in my ASP.NET Core projects in the past for this very purpose. It uses IHostedService in the background. You get far more flexibility than with a timer, and it comes with DI and Logging integration on top of everything else. It's also free and open source with very good documentation. Here's an article on how to integrate it with ASP.NET Core project.

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