标签:des style blog class code java
Topshelf is a framework for hosting services written using the .NET framework. The creation of services is simplified, allowing developers to create a simple console application that can be installed as a service using Topshelf. The reason for this is simple: It is far easier to debug a console application than a service. And once the application is tested and ready for production, Topshelf makes it easy to install the application as a service.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; using Topshelf; using Topshelf.Builders; using Topshelf.Configurators; using Topshelf.HostConfigurators; namespace TopshelfStudy { public sealed class TimeReporter { private readonly Timer _timer; public TimeReporter() { _timer = new Timer(1000) { AutoReset = true }; _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("当前时间:{0}", DateTime.Now); } public void Start() { _timer.Start(); } public void Stop() { _timer.Stop(); } } class Program { static void Main(string[] args) { HostFactory.Run(x => { x.Service<TimeReporter>(s => { s.ConstructUsing(settings => new TimeReporter()); s.WhenStarted(tr => tr.Start()); s.WhenStopped(tr => tr.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("定时报告时间"); x.SetDisplayName("时间报告器"); x.SetServiceName("TimeReporter"); }); } } }
SampleWindowsService.exe install
启动
SampleWindowsService.exe start
如果要卸载也很方便
SampleWindowsService.exe uninstall
最后 Windows Service 没有 Console.WriteLine,我们可以把输出信息输出到文件。
StreamWriter sw = new StreamWriter("e:\\temp\\log.log"); sw.AutoFlush = true; Console.SetOut(sw);
参考网站:
http://www.cnblogs.com/shanyou/archive/2011/05/04/2037008.html
http://www.cnblogs.com/happyframework/p/3601995.html
http://www.cnblogs.com/chenxizhang/archive/2010/04/21/1716773.html
谢谢浏览!
Windows 服务开发框架介绍 - Topshelf,布布扣,bubuko.com
标签:des style blog class code java
原文地址:http://www.cnblogs.com/Music/p/topshelf-1.html