1:首先新建Windows->Windows服務
2:開始鍵入代碼如下:
public partial class Service1 : ServiceBase
{
private System.Timers.Timer myTimer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Debug.WriteLine("MyService Is Started !");
myTimer = new System.Timers.Timer(3000);
myTimer.Elapsed += timer1_Tick_1;
myTimer.Interval = 3000;
myTimer.Enabled = true;
myTimer.Start();
}
private void Work()
{
string Str = DateTime.Now.ToShortDateString();
string Content = string.Format("內容爲:{0}", DateTime.Now.ToString());
DbHelper db = new DbHelper();
DbCommand cmd = db.GetSqlStringCommond("insert into Account values('" + Str + "','" + Content + "')");
db.ExecuteNonQuery(cmd);
}
private Int32 Count = 0;
private void timer1_Tick_1(object sender, EventArgs e)
{
Count++;
Work();
if (Count == 5)
{
string ii = "";
}
}
}
其中string ii = "";中可以設置一個斷點,到發佈以後用來調試
3:在服務空白頁右鍵->添加安裝程序
4:會出現如下2個類,設置他們的屬性:
設置serviceProcessInstaller1 ->Account ->LocalSystem
serviceProcessInstaller1 ->Modiffers -> Public
設置 serviceInstaller1->DisplayName -> “windowsTest” (安裝以後服務的名稱,可以隨便取)
serviceInstaller1->DisplayName -> “window服務編寫測試t” (安裝以後服務的說明,可以隨便取)
serviceInstaller1 -> Modiffers -> Public
serviceInstaller1 ->ServiceName - >FirstService( 未知是做什麼用的)
serviceInstaller1 ->StartType- >Automatic(自動啓動)
然後直接生成,寫2個批處理放在\bin\Debug目錄下,用記事本改一下就好了。代碼如下:
安裝服務.bat
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe WindowsService1.exe
pause
卸載服務.bat
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u WindowsService1.exe
pause
5:然後點擊 安裝服務.bat 進入安裝
6:然後就可以在 我的電腦 ->右鍵 ->管理 ->服務和應用程序 ->服務中 找到該服務了
右鍵啓動它 就OK了
7:關於調試,之前設置過斷點了吧?在vs中找到工具->附加到進程
勾上顯示所有用戶進程 和顯示所有會話中進程 ,找到該進程,點擊附加即可
注意:要調試的話,需要DeBug 模式哦