创建Hangfire Windows服务
由于 hangfire 在 asp.net 环境有不稳定因素,例如 IIS 中应用程序池默认会在闲时自动休眠、隔一段时间会自动重启等问题,在对可用性要求高的场景就会凸显这种不稳定。我认为更合理的方式是使用 Windows Service 来运行 Hangfire,然后另开一个网站作为 Hangfire 的操控面板。
(一)建立Windows service 项目并引入Hangfire
(二)引入Hangfire
工具->Nuget包管理器->程序包管理器控制台
Install-Package Hangfire.Core Install-Package Hangfire.MySqlStorage -Version 1.0.5
注意:hangfire支持.NETFramework,Version=v4.6及以上版本,所以创建项目时选好框架。
这里我是用MySql作为Hangfire的Storage。Hangfire 官方在免费版中只提供了 SqlServer 接入的支持,在收费版多一个 Redis。需要 MongoDB、SqlServer 、PostgreSql、SQLite 等其他 Storages 的可以自己寻找第三方的开源项目,这里有一个官方推荐的扩展清单,清单中列出了一些其他种类的 Storages。
(三)初始化Hangfire服务并添加任务
在App.config中配置数据库链接using Hangfire; using Hangfire.MySql; using HangFireMySql; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace HangFireService { public partial class Service1 : ServiceBase { private BackgroundJobServer _server; public Service1() { InitializeComponent(); //使用MySql作为 数据库存储 ,记得在配置文件中添加数据库连接字符串 var storage = new MySqlStorage("gyy_hangfireservice"); GlobalConfiguration.Configuration.UseStorage(storage); } protected override void OnStart(string[] args) { _server = new BackgroundJobServer(); } protected override void OnStop() { _server.Dispose(); } } }
<add name="gyy_hangfireservice" connectionString="Data Source=192.168.0.106; port=3306; Initial Catalog=gyy_hangfire; uid=****; pwd=****;Allow Zero Datetime=True;charset=utf8;" providerName="MySql.Data.MySqlClient" />
(四)为该Windows 服务添加安装程序
在服务的设计视图中右键,选择添加的安装程序
添加服务器名称,描述,StartType等
(五)使用Visual Studio工具安装和卸载服务
1、用管理员方式打开cmd
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
2、安装命令。找到hangfire 服务的 exe目录
InstallUtil.exe E:\svn\HangFireService\HangFireService\bin\Debug\HangFireService.exe
3、卸载命令。
InstallUtil.exe /u E:\svn\HangFireService\HangFireService\bin\Debug\HangFireService.exe
(六)查看Windows 服务安装是否成功
我的电脑->右键(管理)->服务和应用程序 ->服务。找到生成的服务gyy-hangfire。右键启动即可