在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. vim的配置文件及常用的快捷键

    一些最简单的配置,即在.vimrc中可以写入的配置: 首先,说明一点,在.vimrc文件中,可以用“  把一行的配置注销掉. set nocompatible  “关闭 vi 兼容模式:其中 comp ...

  2. JavaMail 发送邮件案例

    #----------------这两个是构建session必须的字段---------- #smtp服务器 mail.smtp.host=smtp.exmail.qq.com #身份验证 mail. ...

  3. js获取字符串的字节长度

    占用3个字节的范围 U+2E80 - U+2EF3 : 0xE2 0xBA 0x80 - 0xE2 0xBB 0xB3 共 115 个 U+2F00 - U+2FD5 : 0xE2 0xBC 0x80 ...

  4. java 集合(Set2)

    TreeSet: 1.向TreeSet添加元素时 如果元素具有自然特性,那么就按照元素的自然顺序的特点进行排序储存. 如果不具备,就要实现Compareable接口中的compareTo() 方法. ...

  5. java中身份证号15位转18位

    /** * 将15位转换为18位 * @param idCode 15位身份证号 * @return String 18位身份证号 */ public String toEighteen(String ...

  6. GoF--命令设计模式

    定义 将来自客户端的请求传入一个对象,从而使你可用不同的请求对客户进行参数化.用于“行为请求者”与“行为实现者”解耦,可实现二者之间的松耦合,以便适应变化.分离变化与不变的因素. 角色 Command ...

  7. C#读写EXCEL

    using System; using System.Collections; using System.Configuration; using System.Data; using System. ...

  8. div中字垂直居中对齐

    div中的文本水平居中,一般都是用text-align:center;就可以解决,那么垂直居中呢,知道vertiacl-align:middle;但有时候却不起作用:整理下div中文本垂直居中对齐的问 ...

  9. hdu 1695 GCD(莫比乌斯反演)

    GCD Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submiss ...

  10. hdu 4034 Graph (floyd的深入理解)

    Graph Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65768/65768 K (Java/Others)Total Submi ...