《ASP.NET1200例》C#在网页上编写动态时钟

时间:2024-06-16 09:35:20

包含Timer类的命名空间有3个

Timer Class (System.Threading)‎

Timer Class (System.Windows.Forms)‎ 一般用于窗体程序

Timer Class (System.Timers)‎  一般用于控制台程序

using System;

using System.Timers;
class Program
{
public static void Main()
{
Timer t = new System.Timers.Timer();
t.Interval = ;
//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!!");
}
}

Timer Class(using System.Web.UI)一般用于web程序

using System.Web.UI;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
Timer1.Interval = ;
Timer1.Enabled = true;
Timer1.Tick += new EventHandler<EventArgs>(Timer1_Tick); } void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
}

此时前端代码.aspx

<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager> <div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:Timer ID="Timer1"
runat="server">
</asp:Timer> </div>
</form>
</body>