使用Topshelf建立Windows服務

我的使用實例:html

using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using Topshelf;
using Topshelf.Logging;

namespace PPTTask
{
    public class TownCrier
    {
        //private int period = 60000;//兩分鐘
        //private int period = 2000;//測試2秒

        //private Timer _timer = null;
        //readonly static ILog _log = LogManager.GetLogger(typeof(TownCrier));
        //public TownCrier()
        //{
        //    _timer = new Timer(period) { AutoReset = true };
        //    //_timer.Elapsed += (sender, eventArgs) => PPT.ProcessData();
        //    _timer.Elapsed += _timer_Elapsed;
        //      //PPT.ProcessData();
        //}
        //public void Start(){ _timer.Start();}
        //public void Stop() { _timer.Stop(); }

        ///// <summary>
        ///// 達到間隔時發生
        /////     ::在Timer執行的時候就休眠,再也不對數據庫進行查詢,以避免浪費資源
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="s"></param>
        ///// <history>
        /////     add qiuchangling 2017-2-4 15:23:38
        ///// </history>
        //private void _timer_Elapsed(object sender, ElapsedEventArgs s)
        //{
        //    try
        //    {
        //        _timer.Enabled = false;
        //        PPT.ProcessData();
        //    }
        //    finally
        //    {
        //        string sql = string.Format("update PPTTask set Status=4,Remark='windows服務運行異常',UpdateTime='{0}' where DataState=1 and Status =2", DateTime.Now);
        //        DbHelperSQL.ExecuteSql(sql);
        //        _timer.Enabled = true;
        //    }
        //}

        public TownCrier()
        {
        }
        public void Start() {
            Thread th = new Thread(new ThreadStart(StartProcessData));   
            th.IsBackground = true;
            th.Start();
        }
        public void Stop() { }
        private void StartProcessData()
        {
            //PPT.PptToPdfByFolder();

            while (true)
            {
                try
                {
                    PPT.ProcessData();
                }
                catch
                {

                }
                finally
                {
                    string sql = string.Format("update PPTTask set Status=4,Remark='windows服務運行異常',UpdateTime='{0}' where DataState=1 and Status =2", DateTime.Now);
                    DbHelperSQL.ExecuteSql(sql);
                }

                System.Threading.Thread.Sleep(30000);
            }
        }
    }
}

 

 調用時如下代碼便可。git

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Topshelf;
using Topshelf.ServiceConfigurators;
using Topshelf.HostConfigurators;

using System.Data;


namespace PPTTask
{
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.UseLog4Net("Log4Net.config");
                x.Service<TownCrier>(s =>
                {
                    s.ConstructUsing(name => new TownCrier());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });
                x.RunAsLocalSystem();

                x.SetDescription("定時檢查是否有待生成的ppt任務");
                x.SetDisplayName("PPTTask");
                x.SetServiceName("PPTTask");

                //x.OnException(ex =>
                //{
                //    string sql = string.Format("update PPTTask set Status=4,Remark='windows服務運行異常',UpdateTime='{0}' where DataState=1 and Status =2",DateTime.Now);
                //    DbHelperSQL.ExecuteSql(sql);
                //});             
            });

        }
    }
}

 

 

 

 

 

 

http://www.cnblogs.com/jys509/p/4614975.htmlgithub

概述

Topshelf是建立Windows服務的另外一種方法,老外的一篇文章Create a .NET Windows Service in 5 steps with Topshelf經過5個步驟詳細的介紹使用使用Topshelf建立Windows 服務。Topshelf是一個開源的跨平臺的宿主服務框架,支持Windows和Mono,只須要幾行代碼就能夠構建一個很方便使用的服務宿主。sql

引用安裝

一、官網:http://topshelf-project.com/  這裏面有詳細的文檔及下載數據庫

二、Topshelf的代碼託管在 http://github.com/topshelf/Topshelf/downloads   ,能夠在這裏下載到最新的代碼。windows

三、新建一個項目,只須要引用Topshelf.dll 便可,爲了日誌輸出顯示,建議也同時引用Topshelf.Log4Net。程序安裝命令api

  • Install-Package Topshelf
  • Install-Package Topshelf.Log4Net

使用

官網文檔給過來的例子很是簡單,直接使用便可以跑起來,官網文檔地址:http://docs.topshelf-project.com/en/latest/configuration/quickstart.htmlapp

複製代碼
public class TownCrier { readonly Timer _timer; public TownCrier() { _timer = new Timer(1000) {AutoReset = true}; _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now); } public void Start() { _timer.Start(); } public void Stop() { _timer.Stop(); } } public class Program { public static void Main() { HostFactory.Run(x => //1  { x.Service<TownCrier>(s => //2  { s.ConstructUsing(name=> new TownCrier()); //3 s.WhenStarted(tc => tc.Start()); //4 s.WhenStopped(tc => tc.Stop()); //5  }); x.RunAsLocalSystem(); //6  x.SetDescription("Sample Topshelf Host"); //7 x.SetDisplayName("Stuff"); //8 x.SetServiceName("Stuff"); //9 }); //10  } }
複製代碼

程序跑起來後,每隔一秒鐘有輸出,看到的效果以下:框架

配置運行

沒錯,整個程序已經開發完了,接下來,只須要簡單配置一下,便可以當服務來使用了。安裝很方便:測試

安裝:TopshelfDemo.exe install
啓動:TopshelfDemo.exe start
卸載:TopshelfDemo.exe uninstall

安裝成功後,接下來,咱們就能夠看到服務裏多了一個服務:

擴展說明

Topshelf Configuration 簡單配置

官方文檔,對HostFactory 裏面的參數作了詳細的說明:http://docs.topshelf-project.com/en/latest/configuration/config_api.html ,下面只對一些經常使用的方法進行簡單的解釋:

咱們將上面的程序代碼改一下:

複製代碼
            HostFactory.Run(x =>                                 //1  { x.Service<TownCrier>(s => //2  { s.ConstructUsing(name => new TownCrier()); //配置一個徹底定製的服務,對Topshelf沒有依賴關係。經常使用的方式。             //the start and stop methods for the service                     s.WhenStarted(tc => tc.Start()); //4 s.WhenStopped(tc => tc.Stop()); //5  }); x.RunAsLocalSystem(); // 服務使用NETWORK_SERVICE內置賬戶運行。身份標識,有好幾種方式,如:x.RunAs("username", "password"); x.RunAsPrompt(); x.RunAsNetworkService(); 等  x.SetDescription("Sample Topshelf Host服務的描述"); //安裝服務後,服務的描述 x.SetDisplayName("Stuff顯示名稱"); //顯示名稱 x.SetServiceName("Stuff服務名稱"); //服務名稱 }); 
複製代碼

重裝安裝運行後:

 經過上面,相信你們都很清楚 SetDescription、SetDisplayName、SetServiceName區別。再也不細說。

Service Configuration 服務配置

Topself的服務通常有主要有兩種使用模式。

1、簡單模式。繼承ServiceControl接口,實現該接口便可。

實例:

複製代碼
namespace TopshelfDemo { public class TownCrier : ServiceControl { private Timer _timer = null; readonly ILog _log = LogManager.GetLogger(typeof(TownCrier)); public TownCrier() { _timer = new Timer(1000) { AutoReset = true }; _timer.Elapsed += (sender, eventArgs) => _log.Info(DateTime.Now); } public bool Start(HostControl hostControl) { _log.Info("TopshelfDemo is Started"); _timer.Start(); return true; } public bool Stop(HostControl hostControl) { throw new NotImplementedException(); } } class Program { public static void Main(string[] args) { var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); XmlConfigurator.ConfigureAndWatch(logCfg); HostFactory.Run(x => { x.Service<TownCrier>(); x.RunAsLocalSystem(); x.SetDescription("Sample Topshelf Host服務的描述"); x.SetDisplayName("Stuff顯示名稱"); x.SetServiceName("Stuff服務名稱"); }); } } }
複製代碼

2、經常使用模式。

實例:

複製代碼
namespace TopshelfDemo { public class TownCrier { private Timer _timer = null; readonly ILog _log = LogManager.GetLogger( typeof(TownCrier)); public TownCrier() { _timer = new Timer(1000) { AutoReset = true }; _timer.Elapsed += (sender, eventArgs) => _log.Info(DateTime.Now); } public void Start(){ _timer.Start();} public void Stop() { _timer.Stop(); } } class Program { public static void Main(string[] args) { var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); XmlConfigurator.ConfigureAndWatch(logCfg); HostFactory.Run(x => { x.Service<TownCrier>(s => { s.ConstructUsing(name => new TownCrier()); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("Sample Topshelf Host服務的描述"); x.SetDisplayName("Stuff顯示名稱"); x.SetServiceName("Stuff服務名稱"); }); } } }
複製代碼

兩種方式,都使用了Log4Net,相關配置:

複製代碼
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日誌路徑--> <param name= "File" value= "D:\App_Data\servicelog\"/> <!--是不是向文件中追加日誌--> <param name= "AppendToFile" value= "true"/> <!--log保留天數--> <param name= "MaxSizeRollBackups" value= "10"/> <!--日誌文件名是不是固定不變的--> <param name= "StaticLogFileName" value= "false"/> <!--日誌文件名格式爲:2008-08-31.log--> <param name= "DatePattern" value= "yyyy-MM-dd&quot;.log&quot;"/> <!--日誌根據日期滾動--> <param name= "RollingStyle" value= "Date"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" /> </layout> </appender> <!-- 控制檯前臺顯示日誌 --> <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> <mapping> <level value="ERROR" /> <foreColor value="Red, HighIntensity" /> </mapping> <mapping> <level value="Info" /> <foreColor value="Green" /> </mapping> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="Info" /> <param name="LevelMax" value="Fatal" /> </filter> </appender> <root> <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --> <level value="all" /> <appender-ref ref="ColoredConsoleAppender"/> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration>
相關文章
相關標籤/搜索