在WebService中使用Timer
在WebService開發時,有時需要做輪詢操作,可以使用Timer ,注意是System.Timers.Timer,且事件的觸發必須是經過一次WebService調用後。
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
......{
public Service () ......{
//如果使用設計的組件,請取消注釋以下行
InitializeComponent();
}
private System.Timers.Timer timer1;
private System.ComponentModel.IContainer components;
private void InitializeComponent()
......{
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Timers.Timer();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 1000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
......{
using (StreamWriter sw = new StreamWriter(Server.MapPath(".") "TextFile.txt"))
......{
sw.WriteLine(DateTime.Now);
}
}