隨機定時執行任務


間隔時間是一個隨機數,可以設置間隔時間;

可以設置最大次數;

public class RandomTimerEngine
    {
        private System.Threading.Timer _timmer = null;
        private Action<object> _callBack = null;
        private int _minSecond = 0;
        private int _maxSecond = 0;
        private int _maxCount = 0;
        private int _curIndex = 0;
        private bool _isStop = false;

        public RandomTimerEngine(Action<object> callBack) : this(callBack, 0, 10)
        {
        }
        public RandomTimerEngine(Action<object> callBack, int minSecond, int maxSecond):this(callBack, minSecond, maxSecond, 0)
        {
        }
        public RandomTimerEngine(Action<object> callBack, int minSecond, int maxSecond, int maxCount)
        {
            _callBack = callBack;
            _minSecond = minSecond;
            _maxSecond = maxSecond;
            _maxCount = maxCount;
            _timmer = new System.Threading.Timer(this.TimerCallBack, null, Timeout.Infinite, Timeout.Infinite);
        }
        public void Start()
        {
            int randomSecond = this.GetRandomSeconds(_maxSecond);
            _timmer.Change(randomSecond * 1000, Timeout.Infinite);
        }
        public void Stop()
        {
            _isStop = true;
        }

        private void TimerCallBack(object state)
        {
            if (!_isStop)
            {
                if (_maxCount == 0 || (_maxCount > 0 && _curIndex++ < _maxCount))
                {
                    _callBack(state);
                    int randomSecond = this.GetRandomSeconds(_maxSecond);
                    _timmer.Change(randomSecond * 1000, Timeout.Infinite);
                }                
            }
        }

        private int GetRandomSeconds(int maxSeconds = 5)
        {
            return new Random().Next(1, maxSeconds);
        }


    }

使用:

每隔1-5秒執行一次

RandomTimerEngine engine = new RandomTimerEngine((state) => { MessageBox.Show("hello"); }, 0, 5);
engine.Start();

每隔1-5秒執行一次,最多執行10次

RandomTimerEngine engine = new RandomTimerEngine((state) => { MessageBox.Show("hello"); }, 0, 5,10);
engine.Start();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM