2013-01-16 23 views
0

我已經研究瞭如何在C#中進行一般操作,並且我不斷提出調度任務,但是,我不知道這是否是我需要的。這是我想出來的在Silverlight中的確切時間啓動調度計時器

void MainPage_Loaded(Object sender, RoutedEventArgs e) 
    { 
     tomorrowAt8AM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.AddDays(1).Day, 8, 0, 0);//This is always 'tomorrow' at 8 am.. I think. 
     TimeSpan timeSpan = tomorrowAt8AM.Subtract(DateTime.Now); 
     timer.Interval = timeSpan; 
     timer.Tick += new EventHandler(timerTick); 

     queryDB(); 
     timer.Start(); 
    } 

private void timerTick(object sender, EventArgs e) 
    { 
     queryDB(); 

     //Recalculate the time interval. 
     tomorrowAt8AM = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.AddDays(1).Day, 8, 0, 0);//This is always 'tomorrow' at 8 am.. I think. 
     TimeSpan newTimerInterval = tomorrowAt8AM.Subtract(DateTime.Now); 
     timer.Interval = newTimerInterval; 
    } 

的想法是隻找出如何龍是從「現在」,直到「上午8點,明天」,並設置時間跨度爲新的計時器的時間間隔。在我的腦海中,這有效..有沒有更好的方法來做到這一點?由於我改變了它的時間間隔,是否需要重啓計時器?

@Richard Deeming下面是一段代碼,用於測試1月31日的情況。

System.DateTime tomorrowAt8AM = new System.DateTime(DateTime.Now.Year, 2, 1, 8, 0, 0);//This is always the 'next' day at 8 am. 

     while (true) 
     { 
      DateTime temp = new DateTime(DateTime.Now.Year, 1, 31, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); 
      DateTime now = DateTime.Now; 
      System.TimeSpan diff1 = tomorrowAt8AM.Subtract(temp); 
      //Console.WriteLine(diff1.Days); 
      Console.WriteLine("Days: {3}, Hours: {0}, Minutes: {1}, Seconds: {2}", diff1.Hours, diff1.Minutes, diff1.Seconds, diff1.Days); 
      Thread.Sleep(1000); 
     } 

當我執行這個代碼,它似乎剔下來correctly..are你肯定有將是在每月的最後一個問題嗎?

+0

您的測試代碼與您最初發布的代碼不匹配:'tomorrowAt8AM = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.AddDays(1).Day,8,0,0 );':) –

+0

是的..我看到問題出現在哪裏。我最終寫了兩種方法來檢查「明天」是否是新月/年的開始。如果是的話,我會相應處理它。感謝您的洞察力,如果我的程序在15天內突然無法正確更新,將會吸引他們。 – rage

+0

你不需要這麼做 - 'Date.Today.AddDays(1).AddHours(8)'將始終工作。 –

回答

2

您的代碼爲「明天上午8點」是錯誤的。考慮在1月31日發生的事情:

// DateTime.Now == 2013/01/31 
// DateTime.Now.AddDays(1) == 2013/02/01 
tomorrowAt8AM = new DateTime(2013, 1, 1, ... 

您還需要考慮與daylight-saving time會發生什麼。當時鍾前進時,您的代碼將在上午9點執行。當他們回去時,它會在上午7點執行。爲了避免這種情況,你應該使用DateTimeOffset type

DateTimeOffset tomorrowAt8AM = Date.Today.AddDays(1).AddHours(8); 
TimeSpan interval = tomorrowAt8AM.Subtract(DateTimeOffset.Now); 

DispatcherTimer當你改變Interval property將自動更新定時器;您不需要重新啓動計時器。

看着MSDN上的言論,計時器不能保證消防正好8點:

定時器,不能保證當時間間隔發生精確執行,但他們保證不執行在時間間隔發生之前。

您需要測試您的代碼以查看計時器是否足夠滿足您的要求。

+0

我更新了我的問題,你可以看一下嗎? – rage

+0

沒關係,我明白是什麼問題。這個月沒有更新哪個會拋出一切。 – rage