.NET自动服务程序—C#Postedon2006-09-1215:55舞步者阅读(223)评论(0)编辑收藏所属分类:C#.NET自动服务程序—C#应用程序开发中,常常需要实现这样一种功能:让服务器在每天的特定时刻运行固定的程序(或者实现固定的操作),比如让系统在每天的2:00备份数据库数据。要实现这样的功能,我们可以使用Windows服务(Windowsservice)。Windowsservice是一种系统自动的、无人值守的程序(仅存在于WindowsNT、2000和XP操作系统中),它能够在系统启动时开始运行。用户可以通过ServiceControlManager(SCM)Applet或者一些特殊的service-control应用来访问Windowsservice,使服务在没有用户登录到系统之前执行。在.NET出现以前,编写Windows服务是VC++、Delphi才能办到的事情,VB必须使用第三方控件才可以办到,而且编写起来特别的复杂。使用Microsoft®.NETFramework,我们可通过创建作为服务安装的应用程序来方便地创建Windows服务。设计:一个Windows服务程序,按照配置文件中的配置,在指定时刻运行指定程序。流程:启动服务à读取配置文件à启动定时器定时器定时触发(比如每隔30秒)à循环需要运行组件时间à时间到à运行指定程序编写:创建一个WindowsServiceASPectratio="t">将Server1.cs更名为SchedulerServer.cs,双击SchedulerServer.cs打开设计页面,从工具栏的组件中拖Timer控件。更名为SchedulerTimer,并设置Enabled为flase。注意必须是Components里面的Timer控件,WindowsForms里面的Timer控件不行。F7浏览代码可以看到如下代码服务器启动的时候运行:///
///Setthingsinmotionsoyourservicecandoitswork.///protectedoverridevoidOnStart(string[]args){//TODO:Addcodeheretostartyourservice.}服务停止的时候运行:///
///Stopthisservice.///protectedoverridevoidOnStop(){//TODO:Addcodeheretoperformanytear-downnecessarytostopyourservice.}添加写日志函数,用来记录服务的日志:publicstaticvoidWriteLog(stringstrLog){stringstrPath;strPath=System.Environment.SystemDirectory;strPath+=@"\SchedulerServer.txt";FileStreamfs=newFileStream(strPath,FileMode.OpenOrCreate,FileAccess.Write);StreamWriterm_streamWriter=newStreamWriter(fs);m_streamWriter.BaseStream.Seek(0,SeekOrigin.End);m_streamWriter.WriteLine(strLog);m_streamWriter.Flush();m_streamWriter.Close();fs.Close();}自动服务配置文件配置文件保存在系统目录,Windows2000为WinNT\System32,文件名为SchedulerServer.xml,存储了自动服务的所有配置信息,下面我们来看SchedulerServer.xml的格式:
C:\AutoBackup.dll2010-6-802:00?HD:\AutoMail.dll03:00?D註釋:TimeSpan執行頻率,?H小時,?D天,?W周,?M月FilePath设置需要运行的组件的路径RunTime设置需要运行的时间如果有多个程序需要运行,只需要添加
节点程序中添加读取配置文件函数:privateboolReadConf(){try{stringstrPath;XmlDocumentxmldoc=newXmlDocument();XmlNodeListxmlnd;strPath=System.Environment.SystemDirectory+@"\SchedulerServer.xml";xmldoc.Load(strPath);xmlnd=xmldoc.SelectNodes("SchedulerServer/AutoServer");arrConf=newString[2,xmlnd.Count];for(inti=0;i