C#创建windows服务实例与.NET定时访问数据库案例
本文中的案例是使用C#语言来创建windows服务定时访问数据库循环发送手机短信,首先,由于服务是要安装的,所以它运行的时候就需要一个安装类Installer将服务安装到计算机,新建一个后台服务安装类继承自Installer,安装初始化的时候是以容器进行安装的,所以还要建立ServiceProcessInstaller和ServiceInstaller服务信息组件添加到容器安装,在Installer类增加如下代码:
private System.ComponentModel.IContainer components = null;
private System.ServiceProcess.ServiceProcessInstaller spInstaller;
private System.ServiceProcess.ServiceInstaller sInstaller;
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
// 创建ServiceProcessInstaller对象和ServiceInstaller对象
this.spInstaller = new System.ServiceProcess.ServiceProcessInstaller();
this.sInstaller = new System.ServiceProcess.ServiceInstaller();
// 设定ServiceProcessInstaller对象的帐号、用户名和密码等信息
this.spInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.spInstaller.Username = null;
this.spInstaller.Password = null;
// 设定服务名称
this.sInstaller.ServiceName = "SendMessage";
sInstaller.DisplayName = "发送短信服务";
sInstaller.Description = "一个定时发送短信的服务";
// 设定服务的启动方式
this.sInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.spInstaller, this.sInstaller });
}
再添加一个服务类继承自ServiceBase,我们可以重写基类的OnStart、OnPause、OnStop、OnContinue等方法来实现我们需要的功能并设置指定一些属性.由于是定事发送短信的服务,自然少不了Windows记时器,在OnStart事件里我们写入服务日志,并初始化记时器.
private System.Timers.Timer time;
private static readonly string CurrentPath = Application.StartupPath + "\\";
protected override void OnStart(string[] args)
{
string path = CurrentPath + "Log\\start-stop.log";
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("The Service is Starting On " + DateTime.Now.ToString());
sw.Flush();
sw.Close();
fs.Close();
time = new System.Timers.Timer(1000 * Convert.ToInt32(GetSettings("TimeSpan")));
time.Enabled = true;
time.Elapsed += this.TimeOut;
time.Start();
}