Base solution for your next web application
Open Closed

Hangfire Running Job List #8475


User avatar
0
muhittincelik created

Hi,

I want to check running jobs for dont run twice. How can i do that ?

If we set hangfire for background job processor, i think we can not use backgroundjobinfo and other tables because it is empty when jobs running on hangfire.


3 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team

    hi

    You should use hangfire's api to manage jobs.

    Refer to https://docs.hangfire.io/en/latest/

  • User Avatar
    0
    muhittincelik created

    Thanks.

    Solution is;

    using System;
    using System.Linq;
    using Hangfire.Common;
    using Hangfire.Server;
    
    
    namespace Smart.Hangfire
    {
        public class DisableConcurrentExecutionAttribute : JobFilterAttribute, IServerFilter
        {
            private readonly int _timeoutInSeconds;
    
            public DisableConcurrentExecutionAttribute(int timeoutInSeconds)
            {
                if (timeoutInSeconds < 0) throw new ArgumentException("Timeout argument value should be greater that zero.");
    
                _timeoutInSeconds = timeoutInSeconds;
            }
    
            public void OnPerforming(PerformingContext filterContext)
            {
                //var resource = GetResource(filterContext.BackgroundJob.Job);
                var resource = String.Format(
                    "{0}.{1}",
                    filterContext.Job.Type.FullName,
                    filterContext.Job.Method.Name);
                
    
                var timeout = TimeSpan.FromSeconds(_timeoutInSeconds);
    
                var distributedLock = filterContext.Connection.AcquireDistributedLock(resource, timeout);
                filterContext.Items["DistributedLock"] = distributedLock;
            }
    
            public void OnPerformed(PerformedContext filterContext)
            {
                if (!filterContext.Items.ContainsKey("DistributedLock"))
                {
                    throw new InvalidOperationException("Can not release a distributed lock: it was not acquired.");
                }
    
                var distributedLock = (IDisposable)filterContext.Items["DistributedLock"];
                distributedLock.Dispose();
            }
    
            private static string GetResource(Job job)
            {
                return $"{job.Type.ToGenericTypeString()}.{job.Method.Name}";
            }
        }
    }
    

    And add attribute to enqueue job method;

    using Smart.Hangfire;
    
    [DisableConcurrentExecution(300)]
    public async Task .......
    {
    await _backgroundJobManager.EnqueueAsync
    ..
    ..
    }
    
  • User Avatar
    0
    BobIngham created

    NIce work @muhittincelik!