编写一个Windows服务程序,定时从数据库中拿出记录发送邮件

前言:编写一个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

编译

在命令模式下执行:%systemroot%/microsoft.net/framework/v2.0.50727/installUtil.exe D:/项目目录/bin/Debug/可执行文件名.exe

 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值