我已经研究了如何在 C# 中一般地执行此操作,并且我一直想安排一个任务,但是,我不知道这是否是我需要的。这就是我想出的
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);
}
当我执行这段代码时,它似乎正确地打勾。你确定月底会有问题吗?