背景 html
前段时间公司有个需求(天天给业务导出一批数据,以excel的形式经过邮件发送给他)。A说:直接写个服务,判断等于某个时间点,执行一下sql语句,生成excel,写个EmaiHelper发送给他不就得了,这有什么麻烦的?B说:我了个亲娘来,还写服务呢?你还须要搞个timer去判断时间点?多费劲啊,直接写个控制台程序,添加个任务计划,不就搞定了吗?我只想说:大家都是大神,每次都不加点新的东西,还写什么代码,多么没劲啊,前两天看到了topshelf+quartz.net这个东东,能够作个练习了。。。。linux
目的 git
使用topshelf+quartz.net以windows服务形式来导出excel数据github
dapper只是懒得进行数据库相关操做,这个orm能够帮我省下很多工做sql
npoi固然是生成excel的了,一直在用npoi跟excel打交道(无论获取excel数据,仍是生成excel文件)数据库
ioc我使用的是autofactwindows
介绍 app
好了,接下来大致说一下。ide
topshelf官方网站:http://topshelf-project.com/ 工具
github地址:https://github.com/Topshelf/Topshelf/)
topshelf文档:http://docs.topshelf-project.com/en/latest/configuration/quickstart.html
topshelf是建立windows服务的一种方式,相比原生实现ServiceBase、Install.Installer更为简单方便, 咱们只须要几行代码便可实现windows服务的开发。topshelf自己支持windows及linux下mono上部署安装,一样也是开源的。
topshelf相对原生来讲,调试起来比较方便,能够在开发时以控制台的形式直接f5调试,发布时用命令以服务的形式部署。还一个比较有用的特性是支持多实例的部署,这样能够在一台机器上部署多个相对的服务。相似的工具备instsrv和srvany。
topshelf有两种使用方式,下面代码来自官方文档推荐用法
1 public class TownCrier 2 { 3 readonly Timer _timer; 4 public TownCrier() 5 { 6 _timer = new Timer(1000) {AutoReset = true}; 7 _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now); 8 } 9 public void Start() { _timer.Start(); } 10 public void Stop() { _timer.Stop(); } 11 } 12 13 public class Program 14 { 15 public static void Main() 16 { 17 HostFactory.Run(x => //1 18 { 19 x.Service<TownCrier>(s => //2 20 { 21 s.ConstructUsing(name=> new TownCrier()); //3 22 s.WhenStarted(tc => tc.Start()); //4 23 s.WhenStopped(tc => tc.Stop()); //5 24 }); 25 x.RunAsLocalSystem(); //6 26 27 x.SetDescription("Sample Topshelf Host"); //7 28 x.SetDisplayName("Stuff"); //8 29 x.SetServiceName("Stuff"); //9 30 }); //10 31 } 32 }
效果以下图:
没错,一个简单的topshelf程序就是这么简单,接下来,只须要简单配置一下,便可以当服务来使用了。安装很方便:
安装成功后,接下来,咱们就能够看到服务里多了一个服务:
说完topshelf,接下来讲说quartz.net