How to enqueue a job conditionally?

Tags: #<Tag:0x00007f8b978b5c20> #<Tag:0x00007f8b978b5a18>


I am using Hangfire to trigger a database retrieval operation as a background job.

This operation is only supposed to happen once, and can be triggered in multiple ways. (for example, in the UI whenever a user drags and drops a tool, I need to fire that job in the background. But if another tool is dragged and dropped, I don’t want to fire the background job as it’s already prefetched from the database).

This is what my code looks like now:

var jobId = BackgroundJob.Enqueue<BackgroundModelHelper>( (x) => x.PreFetchBillingByTimePeriods(organizationId) );

What I want is some kind of check before I execute above statement, to find if a background job has already been fired; if yes, then do not fire another and if not, then enqueue this .

for example:

bool prefetchIsFired = false;

// find out if a background job has already been fired. If yes, set prefetchIsFired to true.

if (!prefetchIsFired)
     var jobId = BackgroundJob.Enqueue<BackgroundModelHelper>( (x) => x.PreFetchBillingByTimePeriods(organizationId, null) );


How did you finally implement?