这是一款开源的作业调度框架
github地址 https://github.com/HangfireIO/Hangfire
官网 https://www.hangfire.io/
中文文档 https://www.bookstack.cn/read/hangfire-zh/blankquick-start
这边分享一下我从建立项目到部署的一个简单的例子:
首先新建一个空的framework版本的MVC项目
然后执行
PM> Install-Package Hangfire
PM> Install-Package Hangfire.AspNet
这样程序会将hangfire依赖的包下载安装到项目中,然后给项目添加OwinStartup类
然后在Startup类中对hangfire进行初始化
1、使用仪表盘
2、使用sqlserver数据库
3、因为仪表盘只能在本地访问,服务器访问返回401,所以需要权限过滤添加一个账户,在访问仪表盘页面的时候输入账号密码即可进行访问,密码可以直接使用字符串如下,如果想保存为字节类型的则需要将明文的密码转换成字节形式代码如下
using Hangfire;
using Hangfire.Dashboard;
using Hangfire.SqlServer;
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
[assembly: OwinStartup(typeof(HangFireTest.Startup))]
namespace HangFireTest
{
public class Startup
{
private IEnumerable GetHangfireServers()
{
GlobalConfiguration.Configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage("Data Source=10.18.193.200; Initial Catalog=HangfireTest; User ID=sa;Password=123456", new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
UsePageLocksOnDequeue = true,
DisableGlobalLocks = true
});
yield return new BackgroundJobServer();
}
public void Configuration(IAppBuilder app)
{
app.UseHangfireAspNet(GetHangfireServers);
var filter = new BasicAuthAuthorizationFilter(
new BasicAuthAuthorizationFilterOptions
{
SslRedirect = false,
// Require secure connection for dashboard
RequireSsl = false,
// Case sensitive login checking
LoginCaseSensitive = false,
// Users
Users = new[]
{
//new BasicAuthAuthorizationUser
//{
// Login = "Administrator-1",
// // Password as plain text
// PasswordClear = "test"
//},
new BasicAuthAuthorizationUser
{
Login = "admin",//用户名
// Password as SHA1 hash
// Password = new byte[]{ 0x9f,0x71,0x30,0xf4,0x22,0x90,0xd0,0xe0,0xce,0x5a,0x8a,0x7a,0x09,0xd2,0xba,0x75,0x53,0x6d,0x05,0x64 }//密码
PasswordClear="123456"
}
}
});
var options = new DashboardOptions
{
AuthorizationFilters = new[] {
filter
}
};
app.UseHangfireDashboard("/Hangfire", options); //可以改变Dashboard的url
// Let's also create a sample background job
//立即执行
BackgroundJob.Enqueue(() => Debug.WriteLine("Hello world from Hangfire!"));
//BackgroundJob.Enqueue(x => x.AsyncNews());
//立即执行调用后台方法
BackgroundJob.Enqueue(() => new MyTasks().DoAsync());
//可以设置延迟执行
BackgroundJob.Schedule(
() => Console.WriteLine("延迟了2分钟执行!"),
TimeSpan.FromMinutes(2));
//可以设置定时执行循环执行
RecurringJob.AddOrUpdate(x => x.AsyncNews(), "0 */5 * * * ?");//Cron语法 每5分钟执行一次
}
}
}
string password = "qwe123!";//将密码转换为字节形式
using (var cryptoProvider = System.Security.Cryptography.SHA1.Create())
{
byte[] passwordHash = cryptoProvider.ComputeHash(Encoding.UTF8.GetBytes(password));
string result = "new byte[] { " +
String.Join(",", passwordHash.Select(x => "0x" + x.ToString("x2")).ToArray())
+ " } ";
}
这边可以对任务进行很多的操作,细节见官方文档,这边只做一个记录,定时可以使用系统内置的Cron.中的方法,每天每分钟每月等等,需要特殊的定时可以查询Cron语法写入即可
比如我们这边发布后访问http://10.18.193.200:2800/Hangfire
这里将代码中的账号密码输入即可访问到仪表盘
我们可以清楚的查看执行过的作业内容,并可以重新加入队列中进行执行
在周期性作业菜单中可以看到我们设置的每5分钟执行一次的内容,包括立即执行、删除、最后执行时间、下次执行时间等等
在服务器中,可以看到运行的服务器信息,心跳等