asp.net core 3.1 启动添加定时器方法

Add timer method to asp.net core 3.1 startup

我想为一个方法设置一个计时器,所以它每隔 10 分钟调用一次,而应用程序是 运行。

我已经阅读了它,但我还没有找到一个例子,其中它似乎具有相同的 configuration/start up 设置并且时间教程主要使用 main 方法,所以我没有'我还没有弄清楚,我必须将哪些服务添加到我的初创公司 and/or 在哪里放置我的时间和方法。

所以我会把我的计时器设置成 here:

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

然后像这样写我的方法:

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

这是我的创业公司:

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();
            }
            //...        
        }
    }
}

那么我把时间和方法放在哪里呢?如果有人有使用相同启动结构等的示例,将不胜感激。例如,我找到了 this,但它与我的设置不同。

我会将您的计时器设置为 IHostedService。 Microsoft 提供 some documentation on how to do that exactly.

使用 thread 可能会有帮助,但我不确定它是否可以在网络应用程序上正常运行。

ConfigureServices里面调用CallingMyMethodEveryTenSecond()这个方法

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

示例控制台应用程序

参考: Calling a method every x minutes

输出:

代码:

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

我用过 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 项目。