我已經研究瞭如何在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你肯定有將是在每月的最後一個問題嗎?
您的測試代碼與您最初發布的代碼不匹配:'tomorrowAt8AM = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.AddDays(1).Day,8,0,0 );':) –
是的..我看到問題出現在哪裏。我最終寫了兩種方法來檢查「明天」是否是新月/年的開始。如果是的話,我會相應處理它。感謝您的洞察力,如果我的程序在15天內突然無法正確更新,將會吸引他們。 – rage
你不需要這麼做 - 'Date.Today.AddDays(1).AddHours(8)'將始終工作。 –