HangfireIO / Hangfire

An easy way to perform background job processing in .NET and .NET Core applications. No Windows Service or separate process required
https://www.hangfire.io
Other
9.43k stars 1.7k forks source link

Custom Job Filter attribute is not working if it is annotated at the class or method #2438

Open iamSathishMohan opened 2 months ago

iamSathishMohan commented 2 months ago

When the custom job filter attribute is not working when it is annotated at the class or method. It works only when registered as Global job filter.

Replication Steps:

  1. Create LogEverythingAttribute Custom job filter as documented in https://docs.hangfire.io/en/latest/extensibility/using-job-filters.html
  2. Create LongJob as given below
    [LogEverything]
    public class LongJob
    {
     public void Execute()
     {
         Console.WriteLine("LongJob Started at {0}", DateTime.UtcNow.ToLongDateString());
         Task.Delay(6 * 60 * 1000).GetAwaiter().GetResult();
         Console.WriteLine("LongJob Finished at {0}", DateTime.UtcNow.ToLongDateString());
     }
    }
  3. Configure jobs using Configure jobs

    public class ConfigureJobs(IConfiguration configuration, IRecurringJobManager manager, ILogger<ConfigureJobs> logger) : BackgroundService
    {
    private readonly IConfiguration _configuration = configuration;
    private readonly IRecurringJobManager _manager = manager;
    private readonly ILogger<ConfigureJobs> _logger = logger;
    
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            var jobOptions = new DynamicRecurringJobOptions
            {
                QueueName = "scheduler", 
                MisfireHandling = MisfireHandlingMode.Ignorable,
            };
    
            _manager.AddOrUpdateDynamic<LongJob>("LongJob", "scheduler", x => x.Execute(), "*/15 * * * * ?", jobOptions);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An exception occurred while creating recurring jobs.");
        }
    
        return Task.CompletedTask;
    }
    }
  4. Register the scheduler
    
    builder.Services.AddHostedService<ConfigureJobs>();

builder.Services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_180) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseFilter(new AutomaticRetryAttribute { Attempts = 0 }) .UseInMemoryStorage(new InMemoryStorageOptions { IdType = InMemoryStorageIdType.Long, StringComparer = StringComparer.InvariantCultureIgnoreCase // Default value, case-sensitive. }));

builder.Services.AddHangfireServer(opts => { opts.WorkerCount = Environment.ProcessorCount * 5; opts.ServerName = "Test Scheduler"; opts.Queues = ["scheduler"]; opts.StopTimeout = TimeSpan.FromMinutes(3); opts.ShutdownTimeout = TimeSpan.FromMinutes(3); });



only works when the attribute is registered as Global filter using `.UseFilter(new LogEverythingAttribute())`