2012-06-19 80 views
0

我有一個Windows服務設置爲在特定時間運行,它運行第一次,但我似乎無法解決如何告訴它運行第二天,當它結束次..在特定時間運行的Windows服務在第二天運行

這是我努力...

protected override void OnStart(string[] args) 
    { 
     log.Info("Info - Service Start"); 
     string timeToRunStr = "17:11"; 
     var timeStrArray = timeToRunStr.Split(';'); 
     foreach (var strTime in timeStrArray) 
     { 
      timeToRun.Add(TimeSpan.Parse(strTime)); 
     } 
     ResetTimer(); 
    } 

    void ResetTimer() 
    { 
     log.Info("Info - Reset Timer"); 
     try 
     { 
      TimeSpan currentTime = DateTime.Now.TimeOfDay; 
      TimeSpan nextRunTime = timeToRun[0]; 
      foreach (TimeSpan runTime in timeToRun) 
      { 
       if (currentTime < runTime) 
       { 
        nextRunTime = runTime; 
        // log.Info("Info - in loop"); 
        break; 
       } 
       else { 
        TimeSpan test = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 16, 51, 0).Subtract(DateTime.Now); 
        nextRunTime = test; 
       } 
      } 
      _timer = new Timer((nextRunTime - currentTime).TotalSeconds * 1000); 
      log.Info("Info - Timer : " + (nextRunTime - currentTime).TotalSeconds * 1000); 
      log.Info("Info - nextRuntime : " + nextRunTime); 
      log.Info("Info - currentTime : " + currentTime); 
      _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); 
      _timer.Start(); 
     } 
     catch (Exception ex) 
     { 
      log.Error("This is my timer error - ", ex); 
     } 
    } 
+0

爲什麼當一個簡單的控制檯應用程序+任務計劃程序可以開箱即用時,將所有邏輯融入到Windows服務中? – bluevector

+0

theres發生的其他事情,我只需要鍛鍊這個失敗 – Beginner

+0

一些如何添加24小時的測試時間跨度即時猜測 – Beginner

回答

1

查閱這些替代方案:
DateTime of next 3am occurrence

與定時器控制活動,見型號:

class Program 
{ 
    static void my_task(Object obj) 
    { 
     Console.WriteLine("task being performed."); 
    } 

    static TimerCallback timerDelegate; 
    static Timer timer; 

    static void Main(string[] args) 
    { 
     DateTime now = DateTime.Now; 
     DateTime today = now.Date.AddHours(12); 
     DateTime next = now <= today ? today : today.AddDays(1); 

     timerDelegate = new TimerCallback(my_task); 

     //          hence the first   after the next  
     timer = new Timer(timerDelegate, null, next - DateTime.Now, TimeSpan.FromHours(24)); 
    } 
} 
+0

我如何將我的方式 – Beginner