此问题由Lor Manari提出,谢谢!
抱歉源码没有注释,初步学习timer后,想说明在使用timer中可能要注意的事项,欢迎大伙拍砖。
1.注意函数timer_Elapsed的类型为static。
2.在注意1的基础上,atimer的声明应在各函数外,且为static。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers;
namespace timer定时测试
{
public partial class Form1 : Form
{
static System.Timers.Timer aTimer = new System.Timers.Timer();
public Form1()
{
InitializeComponent();
}
///
///
///
private void button1_Click(object sender, EventArgs e)
{
TimeTask();
Console.WriteLine("--end--");
}
private void TimeTask()
{
int hour = DateTime.Now.Hour;
int minute = DateTime.Now.Minute;
aTimer.Interval = 2000;//59000
aTimer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
aTimer.Enabled = true;
//GC.KeepAlive(aTimer);
}
public static void timer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
{
//Console.WriteLine(DateTime.Now.ToString());
//int hour = DateTime.Now.Hour;
//int minute = DateTime.Now.Minute;
if (e.SignalTime.Hour == 21 && e.SignalTime.Minute == 50)
{
aTimer.Interval = 700;
aTimer.Enabled = true;
Console.WriteLine(DateTime.Now.ToString());
//GC.KeepAlive(aTimer);
}
}
}
}
运行结果如下:
![](https://img-my.csdn.net/uploads/201207/18/1342601443_7534.jpg)