简体   繁体   中英

Timer firing on the wrong interval

I am trying to abstract system.threading.timer based off this article: http://www.derickbailey.com/CommentView,guid,783f22ad-287b-4017-904c-fdae46719a53.aspx

However, it seems the timer is firing according to the wrong parameter

In the class below we have this line

timer = new System.Threading.Timer(o => TimerExecute(), null, 1000, 30000);

This should mean wait for 1 second before starting, then fire every 30 seconds

However, the code is firing every one second

what have I done wrong

 public interface ITimer
    {
        void Start(Action action);
        void Stop();
    }

    public class Timer : ITimer, IDisposable
    {
        private TimeSpan timerInterval;
        private System.Threading.Timer timer;
        private Action timerAction;

        private bool IsRunning { get; set; }

        public Timer(TimeSpan timerInterval)
        {
            this.timerInterval = timerInterval;
        }

        public void Dispose()
        {
            StopTimer();
        }

        public void Start(Action action)
        {
            timerAction = action;
            IsRunning = true;
            StartTimer();
        }

        public void Stop()
        {
            IsRunning = false;
            StopTimer();
        }

        private void StartTimer()
        {
            timer = new System.Threading.Timer(o => TimerExecute(), null, 1000, Convert.ToInt32(timerInterval.TotalMilliseconds));
        }

        private void StopTimer()
        {
            if (timer != null)
            {
                timer.Change(Timeout.Infinite, Timeout.Infinite);
                timer.Dispose();
                timer = null;
            }
        }

        private void TimerExecute()
        {
            try
            {
                StopTimer();
                timerAction();
            }
            finally
            {
                if (IsRunning)
                    StartTimer();
            }
        }
    }

You restart the timer for every time it hits TimerExecute. And since it restart well it will trigger after 1 second again. So I would rewrite the TimerExecute to this.

Also your try catch or try finally methods, make sure you actually catch the problems and handle them in some way, not just ignore it.

private void TimerExecute()
    {
        try
        {
            timerAction();
        }
        catch
        {
            //todo
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM