Amit Patil
Amit Patil

Reputation: 1993

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 considering seconds while running so can not compare above time...

Request you to suggest some other way..

Upvotes: 1

Views: 217

Answers (5)

Sasuke Uchiha
Sasuke Uchiha

Reputation: 91

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.

Upvotes: 0

VladV
VladV

Reputation: 10389

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).

Upvotes: 1

aqwert
aqwert

Reputation: 10789

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

Upvotes: 3

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102448

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

Upvotes: 0

Oded
Oded

Reputation: 499382

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.

Upvotes: 3

Related Questions