Stop Hangfire from enqueuing if it is already queued

Is there an easy way to stop a hangfire.io job from enqueuing if it is already queued?

Looking at the jobfilter attribute, nothing stands out how to get the status of something on the server. Can I use connection objects and request storage?

thank

+4
source share
2 answers

I use the following code block to check whether a new task has been added or not, depending on its current state: (I know that at the moment I am only watching the first 1000 tasks. 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 use is simple:

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

//rest
0
source

https://gist.github.com/odinserj/a8332a3f486773baa009

, , .

, [DisableMultipleQueuedItemsFilter].

GlobalJobFilters.Filters.Add(new DisableMultipleQueuedItemsFilter());

0

All Articles