前言:編寫一個Windows服務程序,定時從數據庫中拿出記錄發送郵件。
測試環境:Visual Studio 2005 SP1、Windows Server 2003 SP2
一、新建項目
打開VS2005,新建一個“Windows 服務”項目。
二、添加Timer
展開“工具箱”,在“組件”標簽下找到“Timer”雙擊,這時就添加了一個Timer組件,修改“Name”屬性為“timEmail”、“Enabled”為“false”、“Interval”為“60000”。
接下來要做一些修補工作,不知是VS2005的BUG還是我沒找着地方,在VS2003下是不存在該問題的:剛從“組件”下添加的“Timer”按理說應該來自“System.Timers命名空間”,也只有“System.Timers.Timer”才能在Windows服務程序中正常工作,但是現在這個Timer卻是屬於“System.Windows.Forms.Timer”的。所以得稍作修改,打開“.Designer.cs”文件,修改如下:
#region 組件設計器生成的代碼
//........以上略
/// <summary>
/// 設計器支持所需的方法 - 不要
/// 使用代碼編輯器修改此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
//this.timEmail = new System.Windows.Forms.Timer(this.components);原
this.timEmail = new System.Timers.Timer();//改
this.timEmail.Interval = 60000;
this.ServiceName = "Service1";
}
#endregion
//private System.Windows.Forms.Timer timEmail;原
private System.Timers.Timer timEmail;//改
三、添加配置文件
服務每次調用配置文件,獲取一些基本參數,這樣一些變更就可直接修改配置文件而不必修改代碼。新建ServiceConfig.xml存放於項目“Bin\Debug\”下:
<?xml version="1.0" encoding="utf-8" ?>
<serviceConfig>
<serviceItem
name="sendEmail"
enable="true"
elapsed="60000"
connectionString="your database connection..."
smtp="smtp address"
account="your email account..."
password="your password..." >
</serviceItem>
</serviceConfig>
四、以下是實現代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text; using System.Xml;//操作配置文件
using System.IO;//寫日志
using System.Threading;//使用線程
namespace ClientWindowsService
{
public partial class ClientService : ServiceBase
{
public ClientService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//服務啟動
this.timEmail.Enabled = true;
this.tSendEmail();
}
protected override void OnStop()
{
//服務停止
this.timEmail.Enabled = false;
}
private void timEmail_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//定時器
this.tSendEmail();
}
//開啟新進程發送郵件
private void tSendEmail()
{
Thread t = new Thread(new ThreadStart(sendEmail));
t.Start();
}
//發送郵件函數
private void sendEmail()
{
XmlDocument doc = new XmlDocument();
//添加System.Windows.Forms引用,獲取執行目錄
string configFile = System.Windows.Forms.Application.StartupPath.ToString() + "\ServiceConfig.xml";
doc.Load(@configFile);
XmlElement root = doc.DocumentElement;
foreach (XmlNode node in root)
{
//如果配置文件中開啟服務
if (node.Attributes["name"].Value == "sendEmail" && node.Attributes["enable"].Value == "true")
{
try
{
//讀取數據庫,發送郵件操作,略
}
catch (Exception error)
{
//寫錯誤日志
using (StreamWriter sw = new StreamWriter(System.Windows.Forms.Application.StartupPath.ToString() + @"" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", true, System.Text.Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + ":");
sw.WriteLine(error.ToString());
sw.WriteLine("---------------------------------------------");
sw.Close();
}
}
}
}//end foreach
}
}//end class
}//end namespace
五、布署服務
添加完相應的函數代碼后,從代碼視圖切換到設計視圖,點鼠標右鍵選擇“添加安裝程序” 在設計模式下右鍵-->添加安裝程序-->設置serviceProcessInstaller1的Account為LocalSystem,設置serviceInstaller1的StartType為Automatic。
選擇當前解決方案,設置方案屬性中的"啟動項目"為剛才所添加的項目名稱.按F5運行編譯當前項目,會彈出一個對話框"無法從命令行或者調試器啟動服務,必須首先安裝Windows服務(使用installutil.exe),然后用Server Explorer、Windows服務管理工具或NET START命令啟動它"。錯誤沒有關系,只要當前解決方案\項目文件夾\bin\Debug\文件夾下面多了一個EXE文件就好了。
至此自己需要的服務基本操作已經完成.剩下來的就是編譯.注冊啟動服務了.
Windows服務器注冊停止 打開CMD窗口--開始--運行--輸入CMD,回車 注冊服務命令
cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 InstallUtil.exe D:\HardWareServerService.exe (HardWareServerService為工程的名字)
net start ComputerService (ComputerService是服務的名字)
重新注冊服務
cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 InstallUtil.exe /u d:\HardWareServerService.exe 從您的C# 解決方案下拷貝HardWareServerService.exe文件到D盤HardWareServerService.exe InstallUtil.exe D:\HardWareServerService.exe net start ComputerService
其中D:\HardWareServerService.exe可以修改成"您當前的解決方案目錄\項目名稱\bin\Debug\HardWareServerService.exe"
啟動剛注冊服務: 顯示桌面-在桌面上右擊“我的電腦”,選擇“管理”就可以打計算機管理控制台,選擇“服務和應用程序”里面的“服務”,在右側的服務列表中找到剛注冊的ComputerService服務(默認狀態為停止),選擇該服務右擊啟動所選擇的ComputerService服務就完成了所有的操作,以后每次開機后就自動啟動運行該服務。
http://xiaoou2002.blog.163.com/blog/static/2158666920108153337164/