背景
多數系統都會涉及到“后台服務”的開發,一般是為了調度一些自動執行的任務或從隊列中消費一些消息,開發 windows service 有一點不爽的是:調試麻煩,當然你還需要知道 windows service 相關的一些開發知識(也不難),本文介紹一個框架,讓你讓 console application 封裝為 windows service,這樣你就非常方便的開發和調試 windows service。
TopShelf
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Timers; 7 8 using Topshelf; 9 using Topshelf.Builders; 10 using Topshelf.Configurators; 11 using Topshelf.HostConfigurators; 12 13 namespace TopshelfStudy 14 { 15 public sealed class TimeReporter 16 { 17 private readonly Timer _timer; 18 public TimeReporter() 19 { 20 _timer = new Timer(1000) { AutoReset = true }; 21 _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("當前時間:{0}", DateTime.Now); 22 } 23 public void Start() { _timer.Start(); } 24 public void Stop() { _timer.Stop(); } 25 } 26 27 class Program 28 { 29 static void Main(string[] args) 30 { 31 HostFactory.Run(x => 32 { 33 x.Service<TimeReporter>(s => 34 { 35 s.ConstructUsing(settings => new TimeReporter()); 36 s.WhenStarted(tr => tr.Start()); 37 s.WhenStopped(tr => tr.Stop()); 38 }); 39 40 x.RunAsLocalSystem(); 41 42 x.SetDescription("定時報告時間"); 43 x.SetDisplayName("時間報告器"); 44 x.SetServiceName("TimeReporter"); 45 }); 46 } 47 } 48 }
備注
TopShelf 提高的 API 非常簡單,也提高了和 Log4Net 的集成,結合 Quartz(后面介紹),可以實現任務調度服務。