William
William

Reputation: 1395

Stop Hangfire job from enqueuing if already enqueued

Is there a simple way of stopping a hangfire.io job from enqueuing if one is already enqueued?

Looking at the jobfilterattribute, nothing stands out as how to get the state of anything on the server. Can I use the connection objects and query the store?

Thanks

Upvotes: 10

Views: 4787

Answers (2)

tjackadams
tjackadams

Reputation: 865

Have a look at the following gist by the library owner https://gist.github.com/odinserj/a8332a3f486773baa009

This should prevent the same job from being en-queued more than once by querying the fingerprint.

You can activate it per background job by decorating the method with the attribute [DisableMultipleQueuedItemsFilter].

Or you can enable it globally GlobalJobFilters.Filters.Add(new DisableMultipleQueuedItemsFilter());

Upvotes: 5

Onur Omer
Onur Omer

Reputation: 526

I am using following code block to check to add new job or not, depending on its current state: (I know that i am currently looking at only first 1000 jobs. You can implement your type of logic))

private static bool IsOKToAddJob(string JobName, string QueueName, out string NotOKKey)
    {
        try
        {
            var monapi = JobStorage.Current.GetMonitoringApi();
            var processingJobs = monapi.ProcessingJobs(0, 1000);
            NotOKKey = processingJobs.Where(j => j.Value.Job.ToString() == JobName).FirstOrDefault().Key;

            if (!string.IsNullOrEmpty(NotOKKey)) return false;

            var scheduledJobs = monapi.ScheduledJobs(0, 1000);
            NotOKKey = scheduledJobs.Where(j => j.Value.Job.ToString() == JobName).FirstOrDefault().Key;

            if (!string.IsNullOrEmpty(NotOKKey)) return false;

            var enqueuedJobs = monapi.EnqueuedJobs(QueueName, 0, 1000);
            NotOKKey = enqueuedJobs.Where(j => j.Value.Job.ToString() == JobName).FirstOrDefault().Key;

            if (!string.IsNullOrEmpty(NotOKKey)) return false;

            NotOKKey = null;
            return true;
        }
        catch (Exception ex)
        {
            //LOG your Exception;
        }
    }

And the usage is simple:

if (IsOKToAddJob(YOURJOBNAME, QueueName, out NOTOKKey))
    var id = BackgroundJob.Enqueue(() =>YOURMETHOD()); 

//rest

Upvotes: 0

Related Questions