2016-02-25 32 views
0

我有一個線程在特定時間發射事件來運行程序。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(); 
    }   

這裏是一個PIC表示在定時問題: enter image description here

UPDATE

嘗試了下面的設置,仍然無法正常工作!

只有在參觀時纔開始執行任務。

enter image description here

回答

0

IIS回收計時器需要更改設置。

0

可能在你的IIS Web服務器的設置問題。 IIS應用程序池具有參數(在高級設置中):空閒超時(分鐘)。默認情況下,這個設置是20分鐘。因此,在20分鐘內沒有任何網站查詢時,Web服務器會停止應用程序池進程。

Idle Time-out參數說明。 鏈接到Microsoft Technet

+0

試過沒有成功 –

+0

好的。問題不在應用程序池空閒超時中。另一個建議:可能會在任務代碼中出現一些異常。使用try-catch和log異常來解決問題。 –

+0

那不是因爲它在我訪問該網站後運行正常 –