看个粟子:
1、“新建项目”——“Window服务”
生成的目录结构
双击“MainService.cs”,右键点击“添加安装程序”,自动会生成Projectinstaller.cs文件以及两个安装组件,对两个组件更名并做属性设置:
对服务的启动与停止添加代码
using System; using System.Diagnostics; using System.IO; using System.ServiceProcess; using System.Timers; namespace MainService { public partial class MainService : ServiceBase { private Timer time = new Timer(); public MainService() { InitializeComponent(); } protected override void OnStart(string[] args) { WriteLog("服务启动,时间:" + DateTime.Now.ToString("HH:mm:ss") + "\r\n"); time.Elapsed += new System.Timers.ElapsedEventHandler(MethodEvent); time.Interval = 2 * 1000;//时间间隔为2秒钟 time.Start(); } protected override void OnStop() { WriteLog("服务停止,时间:" + DateTime.Now.ToString("HH:mm:ss") + "\r\n"); } private void MethodEvent(object source, System.Timers.ElapsedEventArgs e) { time.Enabled = false; string result = string.Empty; string startTime = DateTime.Now.ToString("HH:mm:ss"); try { //......... result = "执行成功,时间为:" + startTime; } catch (Exception exp) { result = "失败,原因:" + exp.Message; } finally { WriteLog(result); time.Enabled = true; } } /// <summary> /// 日志记录 /// </summary> /// <param name="logInfo"></param> public void WriteLog(string logInfo) { try { string logDirectory = AppDomain.CurrentDomain.BaseDirectory + "\\Logs"; if (!Directory.Exists(logDirectory)) { Directory.CreateDirectory(logDirectory); } string filePath = logDirectory + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; File.AppendAllText(filePath, logInfo); } catch { } } } }