Windows service
I have written onw windows service..in that i have logic that is some part of code need to execute on certain time.. my service is running in every one min..
e.g.
If (DateTime.Now.ToString("MM/dd/yyyy hh:mm") = "7/23/2010 1:10 ") Then
'execute this logic
End If
But iam facing prob that it is consid开发者_C百科ering seconds while running so can not compare above time...
Request you to suggest some other way..
I am assuming you are running in a loop and comparing against current time - this is a busy wait and not the recommended way of running timed work.
Use a timer in your service and set the interval to 60000 milliseconds. Put the code that needs to run in the tick
event.
See this article about the different timer classes in .NET.
DateTime checkTime = new DateTime(2010, 23, 7, 1, 10, 0);
DateTime now = DateTime.Now;
if(now >= checkTime && now < checkTime.AddSeconds(60))
{ ... }
Try to avoid using ToString
as this type of comparission you can compare datetimes explicitly
DateTime target = DateTime.Parse("7/23/2010 1:10");
if (DateTime.Now >= target) { ... }
So, your code will execute next cycle after the target time (of course, you need to make sure it runs exactly once, if it is what you need).
Would this solve your problem?
If (DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss") = "7/23/2010 1:10:00") Then
'execute this logic
End If
i have done this type of coding in C# in my service let me show you the code where i compare the time
string SetTime = Convert.ToDateTime(dtBackupData.Rows[i]["BackUpTime"].ToString()).ToString("HH:mm");
int t1 = Int32.Parse(SetTime.Replace(":", ""));
int t2 = Int32.Parse(DateTime.Now.ToString("HH:mm").Replace(":", ""));
if (Convert.ToDateTime(dtBackupData.Rows[i]["BackUpTime"].ToString()).ToString("HH:mm") == DateTime.Now.ToString("HH:mm") || t2 > t1)
{your custom code}
hope this solves your problem as it has been working pretty good for me. what the code does for me is that it takes the backup of the database at a specific time.
精彩评论