轉載自:http://www.cnblogs.com/xujie/p/5695673.html
1、新建windows服務項目,我這里選擇的是Framework4.0,沒有選擇高版本是為了防止在服務在一些低版本系統上無法正常運行。
2、添加Windows服務的安裝程序。
在默認Service1設計器界面空白處點擊右鍵->添加安裝程序,系統會自動新建一個帶有默認配置的安裝程序類,如下圖:
新建完安裝程序后,需要給默認的serviceInstaller1和serviceProcessInstaller1做一些基本的屬性設置。如下圖:
以上工作完成,安裝程序配置完畢。
注意:如果不給服務添加安裝程序,后面是沒法把服務安裝至windows系統里的。
3、添加應用程序配置文件(如果有需要的話)。
如果項目有需要,一些應用程序的配置參數可以設置在此文件里(例如:數據庫連接字符串)。
4、編寫windows服務主代碼
-
using System;
-
using System.Collections.Generic;
-
using System.ComponentModel;
-
using System.Data;
-
using System.Diagnostics;
-
using System.IO;
-
using System.Linq;
-
using System.ServiceProcess;
-
using System.Text;
-
using System.Threading.Tasks;
-
-
namespace WinServiceTest
-
{
-
public partial class Service1 : ServiceBase
-
{
-
public Service1()
-
{
-
InitializeComponent();
-
-
System.Timers.Timer timer = new System.Timers.Timer();
-
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
-
timer.Interval = 5000;//每5秒執行一次
-
timer.Enabled = true;
-
}
-
public int count = 0;
-
//定時執行事件
-
private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
-
{
-
//業務邏輯代碼
-
EmailClass mail = new EmailClass();
-
-
mail.Email(count++);
-
}
-
-
protected override void OnStart(string[] args)
-
{
-
this.WriteLog("\n當前時間:" + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + "\n");
-
this.WriteLog("客戶端數據同步服務:【服務啟動】");
-
}
-
-
protected override void OnStop()
-
{
-
this.WriteLog("\n當前時間:" + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss")+ "\n");
-
this.WriteLog("客戶端數據同步服務:【服務停止】");
-
}
-
protected override void OnShutdown()
-
{
-
this.WriteLog("\n當前時間:" + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + "\n");
-
this.WriteLog("客戶端數據同步服務:【計算機關閉】");
-
}
-
-
-
/// <summary>
-
/// 記錄日志
-
/// </summary>
-
/// <param name="msg"></param>
-
private void WriteLog(string msg)
-
{
-
-
//string path = @"C:\log.txt";
-
-
//該日志文件會存在windows服務程序目錄下
-
string path = AppDomain.CurrentDomain.BaseDirectory + "\\log.txt";
-
FileInfo file = new FileInfo(path);
-
if (!file.Exists)
-
{
-
FileStream fs;
-
fs = File.Create(path);
-
fs.Close();
-
}
-
-
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
-
{
-
using (StreamWriter sw = new StreamWriter(fs))
-
{
-
sw.WriteLine(DateTime.Now.ToString() + " " + msg);
-
}
-
}
-
}
-
-
}
-
}
4、安裝與卸載服務

readme里面的內容
-
請將【WinServiceTest】拷貝到D盤或C盤根目錄;
-
安裝服務【管理員身份】運行【SC安裝-發送郵件】即可;
-
卸載服務【管理員身份】運行【SC卸載】即可;
SC安裝-發送郵件:
-
@echo.請稍等,服務啟動......
-
@echo off
-
@sc create GX_To_EMAIL binPath= "D:\WinServiceTest\WinServiceTest\bin\Debug\WinServiceTest.exe"
-
DisplayName=每隔一段時間發送郵件的服務 start= auto
-
@sc description GX_To_EMAIL 定時發送郵件
-
@sc start GX_To_EMAIL
-
@echo off
-
@echo.啟動完畢!
-
@pause
SC卸載:
-
@echo.服務卸載......
-
@echo off
-
@sc stop GX_To_EMAIL
-
@sc delete GX_To_EMAIL
-
@sc stop GX_To_EMAIL
-
@echo off
-
@echo.卸載完畢!
-
@pause