标签:
前言
目录
正文
1 using System; 2 using System.ServiceProcess; 3 4 namespace WindowsServiceTest 5 { 6 public partial class MyFirstWinService : ServiceBase 7 { 8 public MyFirstWinService() 9 { 10 InitializeComponent(); 11 } 12 13 protected override void OnStart(string[] args) 14 { 15 string str = "服务开启"; 16 TestClass.WriteMsgToFile(@"E:\MyProjects\WSExample.txt", str + ",时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 17 } 18 19 protected override void OnStop() 20 { 21 string str = "服务停止"; 22 TestClass.WriteMsgToFile(@"E:\MyProjects\WSExample.txt", str + ",时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 23 } 24 25 protected override void OnContinue() 26 { 27 string str = "服务继续运行"; 28 TestClass.WriteMsgToFile(@"E:\MyProjects\WSExample.txt", str + ",时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 29 } 30 31 protected override void OnPause() 32 { 33 string str = "服务暂停"; 34 TestClass.WriteMsgToFile(@"E:\MyProjects\WSExample.txt", str + ",时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 35 } 36 } 37 38 public static class TestClass 39 { 40 public static void WriteMsgToFile(string fileName, string content) 41 { 42 using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, true)) 43 { 44 sw.WriteLine(content); 45 } 46 } 47 } 48 }
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsServiceTest.exe
Net Start ServiceTest
net stop ServiceTest
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsServiceTest.exe
private System.Timers.Timer timerDelay; protected override void OnStart(string[] args) { try { ///delay start the SynData 30seconds timerDelay = new System.Timers.Timer(30000); timerDelay.Elapsed += new System.Timers.ElapsedEventHandler(timerDelay_Elapsed); timerDelay.Start(); } catch (Exception ex) { this.PrintExceptions(ex); } } void timerDelay_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { timerDelay.Enabled = false; timerDelay.Close(); //你要加的代码 string str = "服务开启"; TestClass.WriteMsgToFile(FilePath, str + ",时间:" + DateTime.Now.ToString(DateFormat)); }
标签:
原文地址:http://www.cnblogs.com/ydp123002/p/5457063.html