SoftwareSavant
SoftwareSavant

Reputation: 9737

Doing something at a particular TIME in .net

I have a process that runs every five minutes and then sleeps. I am wondering if there is an elegant way to do something (anything) when the time is between 11:45PM and midnight on Day.

My first instinct was to get a do something similar to this...

    public bool isItMidNight() {
        return ((DateTime.UtcNow.Hour > 11:54) && DateTime.UtcNow.Hour < 11.59);             
    }

If that value evaluates to true, then do something. If not, keep sleeping and waking un Just psuedo-code BTW. I don't think this will get to production. But that was my idea. Is there a more *strong text*elegant solution

Upvotes: 1

Views: 1250

Answers (3)

Lanorkin
Lanorkin

Reputation: 7504

You can use Timer class, something like this one:

new System.Threading.Timer(myScheduledTask, null, new TimeSpan(hh, mm, ss) - DateTime.Now.TimeOfDay, -1);

Upvotes: 2

48klocs
48klocs

Reputation: 6103

Leave the mechanics of time management to the place best suited for it - I'd recommend using the Windows Task Scheduler.

Let it trigger your application at 11:45 PM and then your application can concentrate on its task without worrying about time and whether another instance of the application has already picked up and run with the task and so on.

Upvotes: 2

Anton Gogolev
Anton Gogolev

Reputation: 115751

Don't know if it qualifies as "elegant", but Quartz.NET is certainly "enterprisey".

Upvotes: 6

Related Questions