Processing jobs in a Windows Service¶

To start using Hangfire in a Windows Service, you’ll need to install Hangfire packages to your console application first. So, use your Package Manager Console window to install it:

  1. PM> Install-Package Hangfire.Core

Then, install the needed package for your job storage. For example, you need to execute the following command to use SQL Server:

  1. PM> Install-Package Hangfire.SqlServer

Hangfire.Core package is enough

Please don’t install the Hangfire package for console applications as it is a quick-start package only and contain dependencies you may not need (for example, Microsoft.Owin.Host.SystemWeb).

After installing packages, all you need is to create a new Hangfire Server instance and start it as written in the Processing background jobs chapter. So, open the source code of the file that describes the service and modify it as written below.

  1. using System.ServiceProcess;
  2. using Hangfire;
  3. using Hangfire.SqlServer;
  4.  
  5. namespace WindowsService1
  6. {
  7. public partial class Service1 : ServiceBase
  8. {
  9. private BackgroundJobServer _server;
  10.  
  11. public Service1()
  12. {
  13. InitializeComponent();
  14.  
  15. GlobalConfiguration.Configuration.UseSqlServerStorage("connection_string");
  16. }
  17.  
  18. protected override void OnStart(string[] args)
  19. {
  20. _server = new BackgroundJobServer();
  21. }
  22.  
  23. protected override void OnStop()
  24. {
  25. _server.Dispose();
  26. }
  27. }
  28. }

If you are new to Windows Services in .NET projects, it is always better to google about them first, but for quick-start scenario you’ll need only to add an installer and optionally configure it. To perform this step just go back to the design view of the service class, right click on it and choose the Add Installer menu item.
Adding installer to Windows Service project
Then build your project, install your Windows Service and run it. If it fails, try look at your Windows Event Viewer for recent exceptions.

  1. installutil <yourproject>.exe

原文:

http://docs.hangfire.io/en/latest/background-processing/processing-jobs-in-windows-service.html