System.Threading.Timer应用

本文介绍了一个使用C#实现的定时任务管理方案,通过System.Threading.Timer类来执行周期性的数据抓取任务。文章详细展示了如何初始化定时器、配置延迟时间和周期时间,并提供了启动、停止定时任务的方法。同时,还讨论了内存管理和资源释放的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 首先Timer 是采用回调机制,所以要保证实力一直被引用着,不然就会被垃圾回收。

所以最好生命全局的Timer实例。

 

其次Timer 由于有2个时间参数,分别为Duetime和PeriodTime前者是首次延迟,后者是下次的间隔时间。

如果使用者在创建Timer实例时填入两个参数。最好在程序内部用Change()函数修改下时间。不然

由于Timer自身的机制,会有多次调用的现象。

----------------------------------------------------------------------参考代码------------------------------------------------------------   #region(菜单栏)
        private void TMSI_Child_Run_Click(object sender, EventArgs e)
        {
            //服务器IP标识
            _ServerName = this.Name.Replace("DBC-OMC-","").Trim();

            strPickFilePath = AppDomain.CurrentDomain.BaseDirectory + "//" + DateTime.Now.ToString("yyyyMMdd") + "-" + _ServerName + strPickFilePath;

            dspPickStatusTip(FRM_Task_BLL.UserTip.Run);

            timerPick = new System.Threading.Timer(new TimerCallback(GetOMCDate), null, lDueTime, 0);

            //程序已经运行即禁用运行设置
            TMSI_Child_Run.Enabled = false;
            //GetOMCDate(null);
        }

        private void TMSI_Child_Stop_Click(object sender, EventArgs e)
        {
            dspPickStatusTip(FRM_Task_BLL.UserTip.Stop);

            if (timerPick != null)
            {
                //由于间隔第一次分配时间和预期时间难以管理所以这里开始跟换时间
                timerPick.Change(-1, -1);

                timerPick.Dispose();

                GC.Collect();
            }

            //暂停计时操作
            TMSI_Child_Run.Enabled = true;
        }
        #endregion

        #region(窗体事件)
        private void FRM_Task_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭窗口的原因说明,如果是父窗体关闭,即子窗体无条件关闭。
            if (e.CloseReason == CloseReason.MdiFormClosing)
            {
                e.Cancel = false;
            }
            else
            {
                Form frmClose = FormFactory.CreatFormObj(FormFactory.FormName.FRM_Close);

                frmClose.StartPosition = FormStartPosition.CenterScreen;

                if (ConfigurationManager.AppSettings["ClosePWD"] != null
                    &&
                    ConfigurationManager.AppSettings["ClosePWD"].ToString() != string.Empty)
                {

                    if (DialogResult.Yes != frmClose.ShowDialog())
                    {
                        e.Cancel = true;
                    }
                }
            }
        }

        private void FRM_Task_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (timerPick != null)
            {
                timerPick.Dispose();
            }

            //由于关闭子窗体所以向父窗体登记自己方便之后再次打开
            FRM_Main.ALConnectionDBC.Add(this.Name);
        }
        #endregion

        #region(绑定数据)
        /// <summary>
        /// 用System.Threading.Timer绑定数据库数据
        /// </summary>
        /// <param name="objValue">无效果的参数</param>
        public void GetOMCDate(object objValue)
        {
            //怕时间间隔太小导致多次进入
            //timerPick.Change(-1,-1);

            dspPickStatusTip.Invoke(FRM_Task_BLL.UserTip.Pick);

            if(strFormatPickTime=="")
                strFormatPickTime = DateTime.Now.ToString("yyyy-MM-dd HH:00:00");

            string strRTBValue = "";

            try
            {
                if (ftbOMC.IsConnection)
                {

                    //获取Oracle数据库数据集
                    DataTable dtOMCData = null;
                    dtOMCData = ftbOMC.dsOracleCollacte(_ServerName, strFormatPickTime).Tables[0];

                    ftbOMC.ImportSQLDataBase("T_CellParameter_G", dtOMCData);

                    strRTBValue = "[server=" + _ServerName + "]-[status=RIGHT]-[description=采集总数" + dtOMCData.Rows.Count.ToString() + "]-[time=" + strFormatPickTime + "]/r/n";
                }
            }
            catch (Exception ex)
            {
                strRTBValue = "[server=" + _ServerName + "]-[status=ERROR]-[description=" + ex.Message + "]-[time=" + strFormatPickTime + "]/r/n";

                //记录日志文件
                ftbOMC.WritLog(strPickFilePath, strRTBValue);
            }

            //在屏幕上返回结果给客户看
            dspOutPutPickWork.Invoke(strRTBValue+"/r/n");

            //Thread.Sleep(1000);

            //状态栏上消息提示
            dspPickStatusTip.Invoke(FRM_Task_BLL.UserTip.Wait);

            //任务完成恢复计时器
            timerPick.Change(lPeriodTime,0);
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值