[英]Add timer method to asp.net core 3.1 startup
我想将 Timer 设置为一个方法,因此在应用程序运行时每隔 10 分钟调用一次。
我已经阅读了它,但我还没有找到一个示例,它似乎具有相同的配置/启动设置,并且时间教程主要使用主要方法,所以我还没有弄清楚,哪些服务我必须添加到我的启动和/或将我的时间和方法放在哪里。
所以我会像这里一样设置我的计时器:
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 提供了一些有关如何准确执行此操作的文档。
使用thread
可能会有所帮助,但我不确定它是否在 web 应用程序上正常工作。
在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();
}
示例控制台应用程序
参考: 每 x 分钟调用一次方法
代码:
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);
}
}
为了这个目的,我过去在我的 ASP.NET 核心项目中使用了Quartz.NET作业调度程序。 它在后台使用 IHostedService。 与使用计时器相比,您可以获得更多的灵活性,并且它在其他一切之上还带有 DI 和 Logging 集成。 它也是免费和开源的,具有非常好的文档。 这是一篇关于如何将其与ASP.NET 核心项目集成的文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.