Search code examples
hangfire

Hangfire - Is there a way to attach additional meta data to jobs when they are created to be able to identify them later?


I am looking to implement Hangfire within an Asp.Net Core application.

However, I'm struggling to understand how best to prevent the user from creating duplicate Hangfire "Fire-and-Forget" jobs.

The Problem

Say the user, via the app, creates a job that does some processing relating to a specific client. The process may take several minutes to complete. I want to be able to prevent the user from creating another job for the same client while there are other jobs for that client still being processed by Hangfire (i.e. there can only be 1 processing job for a specific client at any one time, although several different clients could also each have their own job being processed).

Solution?

I need a way to attach additional meta-data (in this example, the client id) to each job as it is created, which I can then use to interrogate the jobs currently processing in Hangfire to see if any of them relate to the client id in question.

It seems like such a basic feature that would prove so useful for such scenarios, but I'm coming to the conclusion that such a thing isn't supported, which surprises me.

... Unless you know different.

Hangfire looks great, and I'm keen to use it, but this might be a show-stopper for me.

Any advice would be greatly received.

Thanks


Solution

  • I need a way to attach additional meta-data (in this example, the client id) to each job as it is created

    Adding metadata to jobs can be achieved by the mean of hangfire filters. You may have a look at this answer. https://stackoverflow.com/a/57396553/1236044

    Depending on your needs you may use more filters types. For example, the IElectStateFilter may be useful to filter out jobs if another one is currently processing. I you have several processing servers, you will need your own storage solution to handle your own custom currently processing/priority/locking mechanism.