使用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>
相关文章
相关标签/搜索