fireBand
fireBand

Reputation: 957

Trigger event using timer on a specific day and time

I am using System.Timer to trigger an event. Currently I trigger it every 1 hour and check if it matches the configured value (day,time).

But it is possible to trigger this at a specific time? like suppose on Sunday at 12Am.

Windows Task Scheduler would be more appropriate but its not an option.

Thanks in advance

Upvotes: 2

Views: 12917

Answers (3)

Hans Passant
Hans Passant

Reputation: 942010

It isn't clear why you just wouldn't set the timer's Interval to the target date/time. There's a limit on the number of milliseconds, you can time up to 2^31 milliseconds, 27 days. You'll be good as long as you can stay in that range.

    private static void SetTimer(Timer timer, DateTime due) {
        var ts = due - DateTime.Now;
        timer.Interval = ts.TotalMilliseconds;
        timer.AutoReset = false;
        timer.Start();
    }

Upvotes: 9

ShdNx
ShdNx

Reputation: 3213

In a similar situation, I'm using System.Threading.Timer to achieve this. Basically I set its due time to desiredDateTime - DateTime.Now, so that it will tick at desiredDateTime.
If you get another date meanwhile, you can user Timer.Change() to change the tick time to the new date. Don't forget to Dispose() the Timer when you no longer need it!

Upvotes: 0

Emond
Emond

Reputation: 50682

The timer doesn't support this kind of interval but you could check every 20 seconds for the current day and time.

Edit Sorry you are doing that already... why not make the interval half the time left each time you check (A Zeno timer)?

Upvotes: 0

Related Questions