using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System.Text; namespace WinService { public partial class WinService : ServiceBase { private System.Timers.Timer theTimer = new System.Timers.Timer();//定时器 private double timespan;//服务执行的时间间隔 public WinService() { InitializeComponent(); this.theTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.theTimer_Elapsed); } /// <summary> /// 服务启动时执行的函数 /// </summary> /// <param name="args"></param> protected override void OnStart(string[] args) { // TODO: 在此处添加代码以启动服务。 try { theTimer.Start(); timespan = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["timespan"]); theTimer.Interval = timespan * 60 * 1000;//转换为毫秒 } catch (Exception ex) { EventLog.WriteEntry("WinService服务启动","错误:"+ex.Message); } } /// <summary> /// 定时触发事件函数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void theTimer_Elapsed(object sender,System.Timers.ElapsedEventArgs e) { try { BLog(); } catch (Exception ex) { EventLog.WriteEntry("WinService服务", ex.Message + DateTime.Now.ToString()); } } /// <summary> /// 逻辑处理函数 /// </summary> public void BLog() { DateTime nowTime = DateTime.Now; EventLog.WriteEntry("WinService服务", nowTime.ToString()); } /// <summary> /// 服务停止时执行的函数 /// </summary> protected override void OnStop() { // TODO: 在此处添加代码以执行停止服务所需的关闭操作。 EventLog.WriteEntry("WinService服务停止", DateTime.Now.ToString()); } } }