ASP.NET 定时器(System.Timers.Timer)- 服务器端篇

Timer – 计时器或者定时器,跟JavaScript的setInterval有很多相似之处,都是在给定的时间之后做一定的操作。

构造函数
Timer() 初始化 Timer 类的新实例,并将所有属性设置为初始值。
Timer(Double) 初始化 Timer 类的新实例,并将 Interval 属性设置为指定的毫秒数。

主要属性
AutoReset 获取或设置一个布尔值,该值指示 Timer 是否应只引发一次 Elapsed 事件((false) 或重复 (true))。
Enabled 获取或设置一个值,该值指示 Timer 是否应引发 Elapsed 事件。
Interval 获取或设置引发 Elapsed 事件的间隔(以毫秒为单位)。

主要方法
Start() 通过将 Enabled 设置为 true 开始引发 Elapsed 事件。

事件
Elapsed 达到间隔时发生。
Disposed 通过调用释放组件时发生 Dispose 方法。(继承自 Component。)

一个栗子:建一个xml配置文件,根据配置文件在APP开始的时候创建定时器,让它执行我们的方法。

Timer配置文件(XML)

<?xml version="1.0" encoding="utf-8" ?>
<Timer>
  <AutoReset>1</AutoReset>
  <Enabled>1</Enabled>
  <Interval>10000</Interval>
  <Start>1</Start>
  <Suspend>1</Suspend>
</Timer>

读取配置文件类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

namespace WebApplication1
{
    public class ConfigureXML
    {
        public static TimerModel GetValueByCode(string xmlUrl)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlUrl);
            if (doc == null)
            {
                return null;
            }
            XmlNode timerNode = doc.SelectSingleNode("Timer");
            if (timerNode == null)
            {
                return null;
            }

            TimerModel timerModel = new TimerModel();
            try
            {
                timerModel.AutoReset = timerNode.SelectSingleNode("AutoReset").InnerText.Equals("1") ? true : false;
            }
            catch
            {
                timerModel.AutoReset = true;
            }
            try
            {
                timerModel.Enabled = timerNode.SelectSingleNode("Enabled").InnerText.Equals("1") ? true : false;
            }
            catch
            {
                timerModel.Enabled = true;
            }
            try
            {
                timerModel.Interval = Convert.ToDouble("0" + timerNode.SelectSingleNode("Interval").InnerText);
            }
            catch
            {
                timerModel.Interval = 60000d;
            }
            try
            {
                timerModel.Start = timerNode.SelectSingleNode("Start").InnerText.Equals("1") ? true : false;
            }
            catch
            {
                timerModel.Start = false;
            }
            try
            {
                timerModel.Suspend = timerNode.SelectSingleNode("Suspend").InnerText.Equals("1") ? true : false;
            }
            catch
            {
                timerModel.Suspend = true;
            }
            return timerModel;
        }

    }
}

自定义Timer模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    public class TimerModel
    {
        /// <summary>
        /// 获取或设置一个值,该值指示 System.Timers.Timer 是应在每次指定的间隔结束时引发 System.Timers.Timer.Elapsed事件,还是仅在指定的间隔第一次结束后引发该事件。
        /// </summary>
        public bool AutoReset { get; set; }

        /// <summary>
        /// 获取或设置一个值,该值指示 System.Timers.Timer 是否应引发 System.Timers.Timer.Elapsed 事件。
        /// </summary>
        public bool Enabled { get; set; }

        /// <summary>
        /// 获取或设置引发 System.Timers.Timer.Elapsed 事件的间隔
        /// </summary>
        public double Interval { get; set; }

        /// <summary>
        /// 是否启用定时器
        /// </summary>
        public bool Start { get; set; }

        /// <summary>
        /// 是否暂停定时器
        /// </summary>
        public bool Suspend { get; set; }
    }
}

定时器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;

namespace WebApplication1
{
    public class TimerJob
    {
        string timerXmlUrl = @"C:\Users\Administrator\Documents\Visual Studio 2013\Projects\Test20180607\WebApplication1\TimerConfig.xml";

        public TimerJob()
        { }

        public void Start()
        {
            TimerModel timerModel = ConfigureXML.GetValueByCode(timerXmlUrl);
            if (timerModel != null && timerModel.Start)
            {
                Timer timer = timer = new Timer(timerModel.Interval);
                timer.AutoReset = timerModel.AutoReset;
                timer.Enabled = timerModel.Enabled;
                timer.Elapsed += new ElapsedEventHandler(OnElapsedEvent);
                timer.Start();
            }
        }

        /// <summary>
        /// Timer的Elapsed事件执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnElapsedEvent(Object sender, ElapsedEventArgs e)
        {
            //这里就是我们这个定时器要执行的代码,我乱写的_._
            TimerModel timerModel = ConfigureXML.GetValueByCode(timerXmlUrl);
            //控制是否执行逻辑代码
            if (timerModel != null && !timerModel.Suspend)
            {
                Test test = new Test();
                test.GUID = DateTime.Now.ToString();
                DB_TestEntities db = new DB_TestEntities();
                db.Test.Add(test);
                db.SaveChanges();
            }
        }
    }
}

定时器入口(就是启动定时器的地方):Global

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace WebApplication1
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            TimerJob job = new TimerJob();
            job.Start();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}

这样,一个简单的定时器就出来了,通过修改配置文件的参数,可以控制定时器开启/禁用、暂停/继续。至于每个参数是什么意思,可以参考Timer模型。

当然,这样直接去改配置文件也不方便,我们应该弄一个页面,在代码里面去修改配置文件的参数,这样就可以交给不懂代码的人去维护了。

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
System.Timers.Timer和DispatcherTimer都是用于定时执行任务的计时器类,但它们在使用方式和适用场景上有所不同。 System.Timers.Timer是一个多线程计时器,适用于在后台线程执行周期性任务。它是基于底层的System.Threading.Timer实现的,可以在指定的时间间隔内重复执行任务。以下是一个使用System.Timers.Timer的示例: ```csharp static System.Timers.Timer Timer1 = new System.Timers.Timer(); static void Main() { Timer1.Interval = 1000; // 设置时间间隔为1秒 Timer1.Elapsed += new ElapsedEventHandler(PeriodicTaskHandler); // 绑定事件处理程序 Timer1.Start(); // 启动计时器 } static void PeriodicTaskHandler(object sender, ElapsedEventArgs e) { // 执行周期性任务的代码 } ``` DispatcherTimer是一个UI线程计时器,适用于在UI线程上执行周期性任务。它是基于WPF的Dispatcher对象实现的,可以在指定的时间间隔内重复执行任务,并且可以直接更新UI元素。以下是一个使用DispatcherTimer的示例: ```csharp private void StartTimer() { DispatcherTimer dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Tick += OnTimerHandler; // 绑定事件处理程序 dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); // 设置时间间隔为100毫秒 dispatcherTimer.Start(); // 启动计时器 } private void OnTimerHandler(object sender, EventArgs e) { string strTime = DateTime.Now.ToString("HH:mm:ss:fff"); // 获取当前时间 lbTime.Content = strTime; // 更新UI元素 } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郑小晨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值