【发布时间】:2017-05-23 07:22:50
【问题描述】:
我在 startup.cs 文件中创建了一个计时器,如下所示:
public void ConfigureServices(IServiceCollection services)
{
//here i am reading value from appsettings.json
var timeForScheTask = Configuration.GetSection("TimeForScheduledTask");
var time = timeForScheTask.GetValue<string>("TimeToRun"); //it returns 09:00:00 PM
AutoResetEvent autoEvent = null;
autoEvent = new AutoResetEvent(false);
tm = new Timer(Execute, autoEvent, 10000, 10000);
}
下面是定时器的Execute方法:
public void Execute(System.Object stateInfo)
{
if (_counter < 10)
{
//Console.WriteLine("Call #" + _counter);
_counter++;
return;
}
//Console.WriteLine("Final call");
tm.Dispose();
}
我只想在每天晚上 12:00:00 运行一些脚本/查询,我只是想知道在这行代码中应该做些什么,
tm = new Timer(Execute, autoEvent, 1000, 1000);
而不是 1000,1000
通常我不使用 .net/ timer 来运行任何计划任务,但这次我只是在试验这个和那个 .net core,其中微软稍微改变了 timer 的东西。
提前致谢。
【问题讨论】:
-
计时器用于短时间,而不是安排日常任务。例如,如果您的应用程序终止会发生什么?
-
此外 - 问题是什么?你真的遇到问题了吗?你是什么意思“微软改变了计时器”?签名和往常一样。它从不在特定时间工作。它总是与间隔一起工作
-
“微软改变了计时器”我的意思是-adrientorris.github.io/aspnet-core/…
-
至于具体的时间,我再说一遍,计时器不是用于安排日常任务。文档已经展示了如何在特定时间运行 - 只需计算当前时间和目标时间之间的时间跨度并将其作为
dueTime参数传递,例如DateTime.Today.AddHours(17) - DateTime.Now将返回从现在到 17:00 之间的时间间隔 -
如果您想为网站实现计划任务,请使用 HangFire 之类的库。应用程序池可以被回收,线程可以被中止。计时器可能会导致网络场上的多次执行。 Hangfire 负责所有这些工作,并为您的任务添加监控
标签: .net timer asp.net-core-mvc .net-core