Search code examples
c#timerwindows-serviceselapsedtimesystem.timers.timer

System.Timers.Timer How to get the time remaining until Elapse


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?


Solution

  • The built-in timer doesn't provide the time remaining until elapse. 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 => _period;
        public DateTime Next => _next;
        public TimeSpan DueTime => _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();
    }