創建一個簡單的windows服務,每間隔一定時間重復執行批處理文件


創建一個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>
View Code

新建類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();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM