关于hangfire的使用

时间:2025-02-13 10:06:51

hangfire 是一个分布式后台执行服务。用它可以代替ThreadPool.QueunItemWork等原生方法。当然4.5后的 task也是相当好用且功能强大。不过如果想分布式处理并且可监控的话,hangfire绝对满足需求。

我使用hangfire更看重监控层面。

hangfire的执行步骤:

1.客户端创建一个job任务

2.持久化job数据

3.服务端定时fetch数据源

4.如果规则匹配则通过子线程执行job

Client端:

配置:

public void Configuration(IAppBuilder app)
{
app.UseHangfire(config =>
{
config.UseSqlServerStorage("<connection string or its name>");
//config.UseServer(); // 加上这句客户端和服务端就真在一起了
});
}
Enqueue 方法: 放入队列执行。执行后销毁
BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget"));
 
Schedule方法: 延迟执行。第二个参数设置延迟时间。
BackgroundJob.Schedule(() => Console.WriteLine("Delayed"), TimeSpan.FromDays(1));
 
AddOrUpdate方法:重复执行。第二个参数设置cronexpression表达式。
参考quartz文档:http://jingyan.baidu.com/article/a3761b2b8e843c1576f9aaac.html
RecurringJob.AddOrUpdate(() => Console.Write("Recurring"), Cron.Daily);
 
Server端:
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
private readonly BackgroundJobServer _server; public Service1()
{
InitializeComponent(); JobStorage.Current = new SqlServerStorage("connection_string");
_server = new BackgroundJobServer();
} protected override void OnStart(string[] args)
{
_server.Start();
} protected override void OnStop()
{
_server.Dispose();
}
}
}