简体   繁体   English

C#如何检查TimeOfDay是否等于指定的字符串时间

[英]C# How can I check if the TimeOfDay is equal to a specified string time

Basically, I am developing a windows service and I'm asking the computer: if it is xx:xx:xx.xxx then do something. 基本上,我正在开发Windows服务,并询问计算机:如果它是xx:xx:xx.xxx,请执行某些操作。

Unfortunately I'm could not compare it to System.TimeSpan.Parse(): 不幸的是,我无法将其与System.TimeSpan.Parse()进行比较:

timer = new Timer();
this.timer.Interval = 100;
if ((DateTime.Now.TimeOfDay == System.TimeSpan.Parse("02:30:00"))) //24-Hour
{
    //do something
    this.timer.Enabled = true;
}

Also, is there a way to keep the service on watch if the the conditions are met and do the code in the if-block without a timer? 此外,如果满足条件,是否有一种方法可以使服务处于监视状态,并且是否在if块中的代码没有计时器? or do you really need the timer. 还是您真的需要计时器。

You're very seldom going to line up exactly on zero milliseconds with a 100 millisecond timer interval. 您很少会以100毫秒的计时器间隔在0毫秒内精确对齐。 This will cause your comparison as given to fail. 这将导致您的比较失败。 Try [DateTime]::Now.AddMilliseconds(0 - [DateTime]::Now.Millisecond).TimeOfDay for the left side of your comparison. 对于比较左侧,尝试[DateTime]::Now.AddMilliseconds(0 - [DateTime]::Now.Millisecond).TimeOfDay

Also, have you considered just making this a Windows Console app and firing it using Windows Scheduled Tasks? 另外,您是否考虑过将其制作为Windows控制台应用程序并使用Windows Scheduled Tasks触发它? Sometimes that's a better option than writing a service. 有时候,这比编写服务更好。

You can use Quartz.NET library which is a full-featured, open source job scheduling system that can be used from smallest apps to large scale enterprise systems. 您可以使用Quartz.NET库,该库是功能齐全的开源作业调度系统,可用于最小的应用程序到大型企业系统。 It is very useful and easy to use. 它非常有用且易于使用。

Here you can get some tutorials about this. 在这里,您可以获得有关此的一些教程。

You can specify your desired schedule by defining a cron expression which is very flexible. 您可以通过定义非常灵活的cron表达式来指定所需的时间表。

Here is some documentation of this. 这里是一些文档。

if you saying 02:30:00 is the time in 24 format like HH:mm:ss 如果您说02:30:00是24格式的时间,例如HH:mm:ss

you can use like 你可以用像

if("02:30:00".Equals(DateTime.Now.ToString("HH:mm:ss"))
{
// C# code goes here if both matchs
}

update 更新

DateTime.Now.ToString("HH:mm:ss") DateTime.Now.ToString(“ HH:mm:ss”)

this will return only hours:minutes:seconds 这将仅返回小时:分钟:秒

Thank you all for the answer. 谢谢大家的回答。 But, I have decided to do a ranged comparison. 但是,我决定进行远程比较。

timer = new Timer();
this.timer.Interval = 60000;
if(DateTime.Now.TimeOfDay >= System.TimeSpan.Parse("03:00:00") && DateTime.Now.TimeOfDay <= System.TimeSpan.Parse("03:30:00")) { //do something }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM