在C#里关于定时器类有3个:System.Windows.Forms.Timer类、System.Threading.Timer类和System.Timers.Timer类。

System.Windows.Forms.Timer是应用于WinForm中的,它是通过Windows消息机制实现的,类似于VB或Delphi中的Timer控件,内部使用API  SetTimer实现的。它的主要缺点是计时不精确,而且必须有消息循环,Console  Application(控制台应用程序)无法使用。

System.Timers.Timer和System.Threading.Timer非常类似,它们是通过.NET Thread Pool实现轻量、精确的计时,对应用程序、消息没有特别的要求。System.Timers.Timer还可以应用于WinForm,完全取代上面的Timer控件。它们的缺点是不支持直接的拖放,需要手工编码。


        public int wrong = 0;
        System.Timers.Timer time = new System.Timers.Timer();
        
        private void begin_Click(object sender, EventArgs e)
        {
            if (action.Text == "启动监测")
            {
                action.Text = "停止监测";
                label2.Text = "已启动";                 if (time.Interval.ToString() == "100") // The default value of interval is 100s.
                {
                    time.Elapsed += new ElapsedEventHandler(TimeEvent);
                    time.Interval = 1000;
                }
                time.Enabled = true;
            }
            else
            {
                action.Text = "启动监测";
                label2.Text = "已停止";                 time.Enabled = false;
            }         }         private static void TimeEvent(object source, ElapsedEventArgs e)
        {
            int tsec = e.SignalTime.Second;
            int isec = 10;
            if (tsec == isec) //it will be activated at 10s of every minutes.
            {
                if (!Check("http://www.test.com"))
                {
                    string smtp_server="192.168.8.1";
                    int port = 25;
                    string mail_from = "test_from@163.com";
                    string sender="test";
                    string mail_to = "test_to@163.com";
                    string receiver="adminer";
                    string subject = "The site is run out exception on " + DateTime.Now.ToString("yyyyMMddhhmmss");
                    string body = "The site can not open on " + DateTime.Now.ToString() + ",please check it !";
                    try
                    {
                        SendEmail(smtp_server, port, mail_from, sender, mail_to, receiver, subject, body);
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }         private static bool Check(string urlStr)
        {
            HttpWebRequest myWebRequest = null;
            try
            {
                myWebRequest = (HttpWebRequest)WebRequest.Create(urlStr);
                HttpWebResponse res = (HttpWebResponse)myWebRequest.GetResponse();
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    res.Close();
                    return true;
                }
                else
                {
                    res.Close();
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }         public static void SendEmail(string smtp_server, int port, string mail_from, string sender, string mail_to, string receiver, string subject, string body)
        {
            MailAddress from = new MailAddress(mail_from, sender);
            MailAddress to = new MailAddress(mail_to, receiver);
            MailMessage message = new MailMessage(from, to);
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = true;
            message.Subject = subject;
            message.Body = body;             SmtpClient client = new SmtpClient(smtp_server, port);
            //SmtpClient client = new SmtpClient(smtp_server);             // Add credentials if the SMTP server requires them. 
            client.Credentials = CredentialCache.DefaultNetworkCredentials;
            client.Send(message);
        }

使用System.Timers.Timer类实现程序定时执行的更多相关文章

  1. 【C#/WPF】用System.Timers.Timer计时器做浮窗广告

    需求:鼠标静止一段时间后,显示浮窗广告. 思路:界面XAML写好一个专门显示浮窗广告的Canvas,先设为不可见Visibility=”Collapsed”,然后用System.Timers.Time ...

  2. System.Timers.Timer(定时器)

    1.System.Timers命名空间下的Timer类.System.Timers.Timer类:定义一个System.Timers.Timer对象,然后绑定Elapsed事件,通过Start()方法 ...

  3. C# System.Timers.Timer的一些小问题?

    比如设置间隔时间是 1000msSystem.Timers.Timer mytimer = new System.Timers.Timer(1000);问题若响应函数执行的时间超过了 1000 ms, ...

  4. C# --System.Timers.Timer 定时方法

    注意Start() 注意要等Interval 时间间隔 static void Main(string[] args) { System.Timers.Timer t = new System.Tim ...

  5. C# System.Timers.Timer中的坑,程序异常退出后timer依然运行问题

    问题背景 C#小白,由于本公司IM系统服务端(java)是本人独立开发的,加上现在所在项目需要对接IM系统,于是IM的客户端(C#实现)对接工作就交给我了.于是C#小白的我天真的以为只要调用C#端的S ...

  6. .NET System.Timers.Timer的原理和使用(开发定时执行程序)

    概述(来自MSDN) Timer 组件是基于服务器的计时器,它使您能够指定在应用程序中引发Elapsed 事件的周期性间隔.然后可以操控此事件以提供定期处理.例如,假设您有一台关键性服务器,必须每周7 ...

  7. C# System.Timers.Timer定时器的使用和定时自动清理内存应用

    项目比较大有时候会比较卡,虽然有GC自动清理机制,但是还是有不尽人意的地方.所以尝试在项目启动文件中,手动写了一个定时器,定时清理内存,加快项目运行速度. public class Program { ...

  8. C# 定时执行方法: System.Timers.Timer用法示例

    System.Timers.Timer t = new System.Timers.Timer(5000); //设置时间间隔为5秒        private void Form1_Load(ob ...

  9. 简述System.Windows.Forms.Timer 与System.Timers.Timer用法区别

    System.Windows.Forms.Timer 基于窗体应用程序 阻塞同步 单线程 timer中处理时间较长则导致定时误差极大. System.Timers.Timer 基于服务 非阻塞异步 多 ...

随机推荐

  1. 禁止ubuntu的super快捷键

    在mac上安装了ubuntu虚拟机, 但是发现command健(ubuntu中叫super健)被系统占用了, 习惯了command健的同学来说非常不方便, 如何禁用默认的command健呢? You ...

  2. meta标签清理缓存

    如果需要在html页面上设置不缓存,这在<head>标签中加入如下语句: <meta http-equiv="Pragma" content="no-c ...

  3. 使用phpmaill发送邮件的例子

    首先,要下载php_mail软件包 核心代码: index.php <?php include "mail.php"; if (!empty($_POST['to']) &a ...

  4. JS 对象(Object)和字符串(String)互转

    利用原生JSON对象,将对象转为字符串 var jsObj = {}; jsObj.testArray = [1,2,3,4,5]; jsObj.name = 'CSS3'; jsObj.date = ...

  5. Javascript链式调用案例

    jQuery用的就是链式调用.像一条连接一样调用方法. 链式调用的核心就是return this;,每个方法都返回对象本身. 下面是简单的模拟jQuery的代码, <script> win ...

  6. jQuery的选择器小总结

      这一节详细的总结jQuery选择器. 一.基础选择器 $('#info'); // 选择id为info的元素,id为document中是唯一的,因此可以通过该选择器获取唯一的指定元素 $('.in ...

  7. [css] vertical-align和line-height

    原文链接:http://www.zhangxinxu.com/wordpress/2015/08/css-deep-understand-vertical-align-and-line-height/ ...

  8. 彻底理解ThreadLocal

    ThreadLocal是什么 早在JDK 1.2的版本中就提供java.lang.ThreadLocal,ThreadLocal为解决多线程程序的并发问题提供了一种新的思路.使用这个工具类可以很简洁地 ...

  9. 如何设置DIV水平、垂直居中

    一.水平居中 需要设置两点: 1  设置DIV 的width属性即宽度. 2  设置div的margin-left和margin-right属性即可 代码: <div style="w ...

  10. OpenGL的GLUT初始化函数[转]

    OpenGL的GLUT初始化函数 void glutInit(int* argc,char** argv) 初始化GLUT库.对应main函数的形式应是:int main(int argc,char* ...