效果如下:打开服务,可以找到我们新增的一个windows服务,这个demo是定时向一个txt文件输出一句话
生成的以日期命名的txt文件
打开文件结果如下:
全过程梳理
本文将只粗略简单的介绍一下windows服务是如何开发和安装的
一、创建windows服务
如图新建一个Windows服务
进入程序如图
空白服务如下
1 public partial class Service1 : ServiceBase 2 { 3 System.Threading.Timer recordTimer; 4 5 6 public Service1() 7 { 8 InitializeComponent(); 9 } 10 11 12 protected override void OnStart(string[] args) 13 { 14 } 15 16 17 protected override void OnStop() 18 { 19 } 20 } |
只要在OnStart里完成你的功能代码即可。本例中我们做一个定时向本地文件写记录的功能。
创建一个类,用户写文件
1 /// <summary> 2 /// 保存至本地文件 3 /// </summary> 4 /// <param name="ETMID"></param> 5 /// <param name="content"></param> 6 public static void SaveRecord(string content) 7 { 8 if (string.IsNullOrEmpty(content)) 9 { 10 return; 11 } 12 FileStream fileStream = null; 13 StreamWriter streamWriter = null; 14 try 15 { 16 string path = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, string.Format("{0:yyyyMMdd}", DateTime.Now)); 17 18 19 using (fileStream = new FileStream(path, FileMode.Append, FileAccess.Write)) 20 { 21 using (streamWriter = new StreamWriter(fileStream)) 22 { 23 streamWriter.Write(content); 24 25 26 if (streamWriter != null) 27 { 28 streamWriter.Close(); 29 } 30 } 31 32 if (fileStream != null) 33 { 34 fileStream.Close(); 35 } 36 } 37 } 38 catch { } 39 } |
如图那么在Service1中调用
1 public partial class Service1 : ServiceBase 2 { 3 System.Threading.Timer recordTimer; 4 public Service1() 5 { 6 InitializeComponent(); 7 } 8 9 protected override void OnStart(string[] args) 10 { 11 IntialSaveRecord(); 12 } 13 /// <summary> 14 /// 定时检查,并执行方法 15 /// </summary> 16 /// <param name="source"></param> 17 /// <param name="e"></param> 18 private void IntialSaveRecord() 19 { 20 TimerCallback timerCallback = new TimerCallback(CallbackTask); 21 22 AutoResetEvent autoEvent = new AutoResetEvent(false); 23 recordTimer = new System.Threading.Timer(timerCallback, autoEvent, 0, 10000);//其中参数10000表示延时执行服务的时间间隔,毫秒为单位 24 } 25 //方法 26 private void CallbackTask(Object stateInfo) 27 { 28 Show_Java.SaveRecord(string.Format(@"当前记录时间:{0},状况:程序运行正常!", DateTime.Now)); 29 } 30 31 protected override void OnStop() 32 { 33 if (recordTimer != null) 34 { 35 recordTimer.Dispose(); 36 } 37 } 38 } |