当前位置:首页 > Web开发 > 正文

Quartz.NET总结(八)如何按照本身需要配置Topshelf 处事

2024-03-31 Web开发

前面讲了如何使用Topshelf 快速开发windows处事, 不清楚的可以看之前的这篇文章:https://www.cnblogs.com/zhangweizhong/category/771057.html,,

今天说一说Topshelf 的相关配置。

简单配置

官方文档,对HostFactory 里面的参数做了详细的说明: ,下面只对一些常用的要领进行简单的解释:

我们将上面的措施代码改一下:

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区别。不再细说。

处事配置

Topself的处事一般有主要有两种使用模式。

一、简单模式。担任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处事名称"); }); } } }

二、常用模式。

技术图片

实例:

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,相关配置:

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/31851.html