創建一個windows服務項目,增加App.config

<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="AutoBatPosition" value="C:\TestBat\bat\test.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(); } }