0

I am trying to set a function to run at a specific time in a day in c#. This code seems to work but I am not so confident about it. Is there any better way around this?

this is my code

String thetimeis = DateTime.Now.ToString("HH:mm:ss");
DateTime alarmtimeStart = Convert.ToDateTime("12:00:00");
DateTime alarmtimeStop = Convert.ToDateTime("12:02:00");

if (Convert.ToDateTime(thetimeis) > alarmtimeStart && Convert.ToDateTime(thetimeis) < alarmtimeStop)
{
  MessageBox.Show(thetimeis);
}
4

4 回答 4

4

如果您正在寻找更强大的调度作业解决方案,我建议您使用Quartz。对于琐碎的工作,它可能有点矫枉过正,但我​​发现它易于使用并且比推出我自己的解决方案要容易得多。

于 2012-05-05T18:34:16.553 回答
2

是的,有一个更好的方法 - 只需分别比较小时、分钟和秒。

DateTime now = DateTime.Now;
DateTime alarmtimeStart = Convert.ToDateTime("12:00:00");
DateTime alarmtimeStop = Convert.ToDateTime("12:02:00");

if (now.Hour >= alarmtimeStart.Hour && now.Minute >= alarmtimeStart.Minute && now.Second >= alarmtimeStart.Second && now.Hour <= alarmtimeStop.Hour && now.Minute <= alarmtimeStop.Minute && now.Second <= alarmtimeStop.Second)
{
    MessageBox.Show(thetimeis);
}
于 2012-05-05T18:30:34.713 回答
2

你不能直接比较日期的 TimeOfDay 属性吗?

编辑:

TimeSpan thetimeis = DateTime.Now.TimeOfDay;
TimeSpan alarmtimeStart = new TimeSpan(12, 0, 0);
TimeSpan alarmtimeStop = new TimeSpan(12, 2, 0);

if (thetimeis >= alarmtimeStart && thetimeis < alarmtimeStop)
{
   MessageBox.Show(thetimeis);
}
于 2012-05-05T18:40:05.737 回答
1

我有点困惑为什么你需要这么多的转换,以下不是更好吗?

if (DateTime.Now > alarmtimeStart && DateTime.Now < alarmtimeStop) 
{ 
  MessageBox.Show(thetimeis); 
} 
于 2012-05-05T18:38:48.433 回答