views:

346

answers:

2

Using C#, how may I get the time remaining (before the elapse event will occur) from a System.Timers.Timer object?

In other words, let say I set the timer interval to 6 hours, but 3 hours later, I want to know how much time is remaining. How would I get the timer object to reveal this time remaining?

+4  A: 

The built-in timer doesn't do this. You'll need to create your own class which wraps a timer and exposes this info.

Something like this should work.

public class TimerPlus : IDisposable
{
    private readonly TimerCallback _realCallback;
    private readonly Timer _timer;
    private TimeSpan _period;
    private DateTime _next;

    public TimerPlus(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
    {
        _timer = new Timer(Callback, state, dueTime, period);
        _realCallback = callback;
        _period = period;
        _next = DateTime.Now.Add(dueTime);
    }

    private void Callback(object state)
    {
        _next = DateTime.Now.Add(_period);
        _realCallback(state);
    }

    public TimeSpan Period
    {
        get
        {
            return _period;
        }
    }

    public DateTime Next
    {
        get
        {
            return _next;
        }
    }

    public TimeSpan DueTime
    {
        get
        {
            return _next - DateTime.Now;
        }
    }

    public bool Change(TimeSpan dueTime, TimeSpan period)
    {
        _period = period;
        _next = DateTime.Now.Add(dueTime);
        return _timer.Change(dueTime, period);
    }

    public void Dispose()
    {
        _timer.Dispose();
    }
}
Sam
Above and beyond the call, but checked you for your efforts. Thanks, you are very kind. I already have a method that will calculate how much time should be remaining, but wanted to confirm it with output from the actual timer object itself. To bad it isn't inherently provided.
LonnieBest
+1 Thanks for this useful code, Sam !
BillW
Yeah, he wrote that fast too. Impressive.
LonnieBest
+2  A: 

I guess the best method is to hold the start time in a variable and then calculate the elapsed time as

TimeSpan t = DateTime.Now - StartTime;
signetro
I agree. But, had to check Sam for his efforts; he wrote a class to help me. Super kind. Thank you both.
LonnieBest