標籤:des style blog class code java
關於 TopShelf
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.
樣本第一步:建立一個 C# 控制台應用程式。第二步:用 Nuget 引用 TopShelf 和 Log4net。第三步:貼出下面的代碼。
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"); }); } }}第四步:編譯、Release 產生。把 Release 檔案夾 Copy 到 C 盤。第五步:以管理員身份運行 cmd,安裝、啟動。
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
謝謝瀏覽!