用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c#代码库

定时器

2016-10-26 作者: sidecore举报

[c#]代码库

    /// <summary>
    /// 定时器
    /// </summary>
    public class ScheduledControlEngine
    {
        private Action<DateTime> _action;
        private DateTime _lastTime;
        private bool _flag;
        private int _cycle;
        private System.Threading.Thread _mainThread;

        /// <summary>
        /// 定时器
        /// </summary>
        /// <param name="firstStartTime">第一次启动基准时间</param>
        /// <param name="cycle">在第一次启动时间基础上,执行循环,单位为秒</param>
        public ScheduledControlEngine(DateTime firstStartTime, int cycle)
        {
            _cycle = cycle;
            _lastTime = firstStartTime;
            _mainThread = new System.Threading.Thread(Loop);
        }

        public ScheduledControlEngine(DateTime firstStartTime, int cycle, Action<DateTime> action)
        {
            _cycle = cycle;
            _lastTime = firstStartTime;
            _mainThread = new System.Threading.Thread(Loop);
            RegisterCallback(action);
        }

        public void RegisterCallback(Action<DateTime> action)
        {
            _action += action;
        }

        private void Loop()
        {
            _flag = true;
            while (_flag)
            {
                var now = DateTime.Now;

                if ((now - _lastTime).TotalSeconds > 0)
                {
                    _lastTime = NextTime();
                    _action(now);
                }
                System.Threading.Thread.Sleep(1000 * 1);
            }
        }

        private DateTime NextTime()
        {
            var now = DateTime.Now;
            var tsp = now - _lastTime;
            var interval = (int)(tsp.TotalSeconds / _cycle);
            var nextTime = interval * _cycle;
            var time = _lastTime.AddSeconds(nextTime).AddSeconds(_cycle);
            return time;
        }

        public void Start()
        {
            _mainThread.Start();
        }

        public void Stop()
        {
            _flag = false;
        }

    }


static void Main(string[] args)
        {
            DateTime firstRunTime;
            int cycle=60;
            System.Console.WriteLine("系统启动中……");
            ScheduledControlEngine controlEngine = new ScheduledControlEngine(firstRunTime, cycle, AutoTrans);
            controlEngine.Start();
        }


网友评论    (发表评论)

共2 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...