關鍵點視紅字
1.新建一個Windows Service的項目
範例程式碼--
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
Work _WorkObj = new Work();//自訂的物件
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_WorkObj.StartWorkThread();//自訂的method 用來啟動Timer控制項
}
}
}
2.自訂一個class -> 到時要給Service1的OnStart()method呼叫
範例程式碼--
namespace WindowsService1
{
public class Work
{
//注意: 是Sysytem.Timers.Timer,不是System.Windows.Forms.Timer,如果工具箱理没有,就要右键點"Choose Items...(選擇工具...)"把它添加上)
private System.Timers.Timer timer2= new System.Timers.Timer();
public Work()
{
timer2.Enabled = true;
timer2.Interval = 10000;//引發System.Timer.Timer.Elapsed的時間間隔
//注意:是引發Elapsed event,而不是System.Windows.Forms.Timer的Tick event
timer2.Elapsed+=new System.Timers.ElapsedEventHandler(timer2_Elapsed);
}
public void StartWorkThread()
{
timer2.Start();//引發System.Timer.Timer.Elapsed 事件
}
private void timer2_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
{
/*
妳要做的事
*/
}
}
}
星期四
用C#創建 Windows Service + Timer 的致命關鍵點
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言