创建一个windows服务项目,增加App.config

<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="AutoBatPosition" value="C:TestBatat est.bat" /> <add key="IntervalSecond" value="30"/> </appSettings> </configuration>
新建类BusinessLogic.cs,主要的业务逻辑都在此类中
public class BusinessLogic { System.Timers.Timer timer; String autoBat = System.Configuration.ConfigurationManager.AppSettings["AutoBatPosition"]; //批处理文件的路径 public static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();//执行间隔 public void Run() { int intervalSecond = int.Parse(System.Configuration.ConfigurationManager.AppSettings["IntervalSecond"]); timer = new System.Timers.Timer(intervalSecond * 1000); //间隔秒 timer.AutoReset = true; timer.Enabled = true; //一直执行 timer.Elapsed += new ElapsedEventHandler(DoMerger); timer.Start(); } //调用批处理 private void DoMerger(object source, System.Timers.ElapsedEventArgs e) { try { log.Info("开始"); log.Info("执行批处理开始"); System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = autoBat; process.StartInfo.UseShellExecute = false; //此处必须为false否则引发异常 process.Start(); process.WaitForExit(); log.Info("执行批处理结束"); log.Info("结束"); } catch (Exception ex) { log.Error(ex.ToString()); } } public void Stop() { timer.Close(); } }
BusinessLogic.cs类创建完成,那么接下来就是调用了,打开Service1.cs,切换到代码视图
public partial class Service1 : ServiceBase { BusinessLogic logic = null; public Service1() { InitializeComponent(); logic = new BusinessLogic(); } protected override void OnStart(string[] args) { logic.Run(); } protected override void OnStop() { logic.Stop(); } }