在项目中引入后台任务时,通常我们会在windows环境下使用命令行程序结合计划任务或者直接生成windows服务来管理任务。然而,随着.net core的跨平台特性,linux环境下的计划任务虽然可用,但与传统方式类似,缺乏图形界面,执行结果只能通过查看服务器日志来确认。经过评估,我们决定采用hangfire来满足需求,因为它不仅提供图形化的用户界面,还简化了后台任务的注册过程。
Hangfire的安装和使用非常简单。首先,在项目中通过包管理器安装Hangfire:
PM> Install-Package Hangfire
对于Asp.Net Core项目,在Startup.cs文件的ConfigureServices方法中添加Hangfire的注册:
services.AddHangfire(x => x.UseSqlServerStorage("connection string"));这里的connection string是数据库连接字符串,我选择使用的是Sql Server,但你也可以使用Redis、Mysql等其他数据库。
注册完成后,在Configure方法中添加以下代码:
app.UseHangfireServer(); app.UseHangfireDashboard();
项目启动后,Hangfire会进行相关数据结构的Migration。启动成功后,通过项目地址加上/Hangfire可以查看Hangfire是否正常运行,看到如下界面表示基本没有问题。

Hangfire的基本使用非常简单,主要依赖以下几个静态方法:
//执行后台脚本,仅执行一次
BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget!"));
//延迟执行后台脚本,仅执行一次
BackgroundJob.Schedule(
() => Console.WriteLine("Delayed!"),
TimeSpan.FromDays(7));
//周期性任务
RecurringJob.AddOrUpdate(
() => Console.WriteLine("Recurring!"),
Cron.Daily);
//等上一任务完成后执行
BackgroundJob.ContinueWith(
jobId, //上一个任务的jobid
() => Console.WriteLine("Continuation!"));在.Net Core中,依赖注入(DI)无处不在。如果你在使用Hangfire时不小心,你可能会遇到各种问题。例如以下代码:
public class HomeController : Controller
{
private ILogger _logger;
public HomeController(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger();
}
public IActionResult Index()
{
_logger.LogInformation("start index");
BackgroundJob.Enqueue(() => _logger.LogInformation("this a job!"));
return View();
}
} 项目启动后,虽然可以正常访问,但在Hangfire后台会看到如下错误:

错误信息大致意思是不能使用接口或者抽象类,这是因为Hangfire无法找到实例。为了让Hangfire支持DI,我们需要创建一个MyActivator类,使其继承Hangfire.JobActivator类,代码如下:
系统简介1:安全可靠: 在微软主推的.NET开发平台上,采用业界领先的ASP.NET技术和C#语言开发,不仅安全可靠,并能保证系统的高性能运行。2:简单易用:版纳武林DIY企业建站系统真正做到以人为本、以用户体验为中心,能使您快速搭建您的网站。后台管理操作简单,一目了然,没有夹杂多余的功能和广告。3:布局易改:版纳武林DIY企业建站系统采用的是博客形式的风格管理,让您真正感受到我的地盘听我的.4:
public class MyActivator : Hangfire.JobActivator
{
private readonly IServiceProvider _serviceProvider;
public MyActivator(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider;
public override object ActivateJob(Type jobType)
{
return _serviceProvider.GetService(jobType);
}
}通过重写ActivateJob方法,使其从我们的IServiceProvider中获取返回类型。
接下来,我们编写两个后台任务,CheckService和TimerService。CheckService的Check方法在执行计划时,会再次调用Hangfire来定时启动TimerService:
CheckService:
public interface ICheckService
{
void Check();
}
public class CheckService : ICheckService
{
private readonly ILogger _logger;
private ITimerService _timerService;
public CheckService(ILoggerFactory loggerFactory,
ITimerService timerService)
{
_logger = loggerFactory.CreateLogger();
_timerService = timerService;
}
public void Check()
{
_logger.LogInformation($"check service start checking, now is {DateTime.Now}");
BackgroundJob.Schedule(() => _timerService.Timer(), TimeSpan.FromMilliseconds(30));
_logger.LogInformation($"check is end, now is {DateTime.Now}");
}
} TimerService:
public interface ITimerService
{
void Timer();
}
public class TimerService : ITimerService
{
private readonly ILogger _logger;
public TimerService(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger();
}
public void Timer()
{
_logger.LogInformation($"timer service is starting, now is {DateTime.Now}");
_logger.LogWarning("timering");
_logger.LogInformation($"timer is end, now is {DateTime.Now}");
}
} 目前还无法使用,我们必须在Startup中注册这两个服务:
services.AddScoped(); services.AddScoped ();
然后在HomeController中进行如下修改:
public IActionResult Index()
{
_logger.LogInformation("start index");
BackgroundJob.Enqueue(c => c.Check());
return View();
} 一切就绪后,只需覆盖原始的Activator。我们可以在Startup.cs的Configure方法中使用如下代码:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
GlobalConfiguration.Configuration.UseActivator(new MyActivator(serviceProvider));
……
……
} 再次启动项目,我们的后台任务就会成功执行,截图如下:

参考资料:
- Hangfire 官网:https://www.php.cn/link/2418c4e3de622a573d9233ad9ab707a3
- Hangfire DI in .net core : https://www.php.cn/link/195f817357e95f7d4b3b776ff7c4c596
- Demo 地址:https://www.php.cn/link/2e8b0ad62c8a9f3c5af58a346076e638









