包含Timer类的命名空间有3个
一般用于窗体程序
一般用于控制台程序
using System; using System.Timers;
class Program { public static void Main() { Timer t = new System.Timers.Timer(1000); t.Interval = 2000; //t.AutoReset = false; //每到指定时间Elapsed事件是触发一次(false),还是一直触发(true) t.Enabled = true; //是否触发Elapsed事件 t.Elapsed += new ElapsedEventHandler(t_Elapsed); Console.WriteLine("Press the Enter key to exit the program."); //从标准输入流读取下一行 Console.ReadLine(); // Keep the timer alive until the end of Main. GC.KeepAlive(t); } static void t_Elapsed(object sender, ElapsedEventArgs e) { Console.WriteLine("hello world!!"); } }
(using System.Web.UI)一般用于web程序
using System.Web.UI; protected void Page_Load(object sender, EventArgs e) { Label1.Text = DateTime.Now.ToString(); Timer1.Interval = 1000; Timer1.Enabled = true; Timer1.Tick += new EventHandler(Timer1_Tick); } void Timer1_Tick(object sender, EventArgs e) { Label1.Text = DateTime.Now.ToString(); }
此时前端代码.aspx