我有一个线程在特定时间发射事件来运行程序。MVC 5 - Ninject - 任务线程奇怪地运行
我确实希望网站能够完全控制流程,这就是为什么我将它作为循环的长期线程构建到网站中的原因。
问题是我安排了一个任务发生在一个特定的时间,它几乎随机发生(也许当我加载页面)。看起来好像这个网络应用程序睡眠所有的线程,直到它被使用或什么。
下面是代码:
public void run()
{
Task.Factory.StartNew(() =>
{
while (true)
{
var lastDate = InternalEventLogger.GetLastDateTime();
if (DateTime.Now >= lastDate.AddDays(1))
{
System.Diagnostics.Debug.WriteLine(DateTime.Now);
System.Diagnostics.Debug.WriteLine(lastDate.AddDays(1));
InternalEventLogger.RefreshLog();
}
bool needUpdate = false;
System.Diagnostics.Debug.WriteLine("this");
List<Event> tempList = new List<Event>(this.evtList.getList());
foreach (Event evt in this.evtList.getList())
{
if (!evt.status.Equals("success"))
continue;
if (evt.nextRun <= DateTime.Now)
{
var tempEvt = evt;
System.Diagnostics.Debug.WriteLine("time to run: "+evt.name);
tempList.Remove(evt);
tempEvt.nextRun = evt.nextRun.AddMinutes(evt.interval);
tempEvt.lastRan = DateTime.Now;
tempList.Add(tempEvt);
needUpdate = true;
if (tempEvt.runLocation != null)
Task.Factory.StartNew(() =>
{
Process p = new Process();
p.StartInfo.FileName = tempEvt.runLocation;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
string output = p.StandardOutput.ReadToEnd();
string err = p.StandardError.ReadToEnd();
InternalEventLogger.WriteLog(output);
InternalEventLogger.WriteLog("// ------------- ERROR -------------- \n" + err);
p.WaitForExit();
});
}
}
if (needUpdate)
{
this.evtList.setList(tempList);
this.evtList.serialize(ConfigurationManager.AppSettings["xmlEventLocation"]);
}
Thread.Sleep(10000);
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
冉从:
private static void RegisterServices(IKernel kernel)
{
evtManager = new EventManager(ConfigurationManager.AppSettings["xmlEventLocation"]);
evtManager.run();
// Initalize Event Logger
new InternalEventLogger();
}
UPDATE
尝试了下面的设置,仍然无法正常工作!
只有在参观时才开始执行任务。
试过没有成功 –
好的。问题不在应用程序池空闲超时中。另一个建议:可能会在任务代码中出现一些异常。使用try-catch和log异常来解决问题。 –
那不是因为它在我访问该网站后运行正常 –