新建windows服务项目
第一步:新建windows服务项目

第二步:编写执行方法与时间控制器
1 public partial class Service1 : ServiceBase 2 { 3 public Service1() 4 { 5 InitializeComponent(); 6 } 7 8 /// <summary> 9 /// 服务启动时执行的方法 10 /// </summary> 11 /// <param name="args"></param> 12 protected override void OnStart(string[] args) 13 { 14 15 TimerMethod(); 16 } 17 18 /// <summary> 19 /// 服务停止的执行方法 20 /// </summary> 21 protected override void OnStop() 22 { 23 24 } 25 26 27 28 /// <summary> 29 /// 自定义执行方法 30 /// </summary> 31 private void TimerMethod() 32 { 33 34 System.Timers.Timer timer = new System.Timers.Timer(1000);//实例化Timer类,设置间隔时间为1000毫秒; 35 timer.Elapsed += new System.Timers.ElapsedEventHandler(myMethod);//到达时间的时候执行事件; 36 timer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件; 37 timer.AutoReset = true;//设置是执行一次(false)还是一直执行(true); 38 } 39 private void myMethod(object source, System.Timers.ElapsedEventArgs e) 40 { 41 42 WriteLog(); 43 //实现方法 44 } 45 /// <summary> 46 /// 日志方法 47 /// </summary> 48 public static void WriteLog() 49 { 50 string path = AppDomain.CurrentDomain.BaseDirectory; 51 path = System.IO.Path.Combine(path, "Logs\\"); 52 if (!System.IO.Directory.Exists(path)) 53 { 54 System.IO.Directory.CreateDirectory(path); 55 } 56 string fileFullName = System.IO.Path.Combine(path, string.Format("{0}.txt", "Error" + DateTime.Now.ToString("yyyyMMdd"))); 57 using (StreamWriter output = System.IO.File.AppendText(fileFullName)) 58 { 59 output.WriteLine(DateTime.Now.ToString()); 60 output.Close(); 61 } 62 } 63 }
2:如何部署
文档:
https://docs.microsoft.com/zh-cn/dotnet/framework/windows-services/how-to-install-and-uninstall-services(建议使用:PowerShell )
浙公网安备 33010602011771号