Initialization of Hangfire servers for multitenants application

I am facing issue with add Hangfire servers for multi tenant application. In my application startup I am looping through all tenants and initialize and add set of jobs for each tenant. It is adding servers in each tenant database but the jobs are added only to first tenant database. I don’t see any job in other tenants databases and dashboard. Following is the code I am trying:

foreach (var tenant in TenantConvention.GetTenants())
{

            GlobalConfiguration.Configuration
             .UseSqlServerStorage(DbServer.GetConnectionString(tenant));

            var sqlStorage = new SqlServerStorage(DbServer.GetConnectionString(tenant));

            app.UseHangfireDashboard($"/dashboard/{tenant}-Jobs", new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthFilter() }

            }, sqlStorage);

            var options = new BackgroundJobServerOptions
            {                   
                ServerName = tenant//string.Format("{0}.{1}", tenant, Guid.NewGuid().ToString())
            };

            var jobStorage = JobStorage.Current;
            app.UseHangfireServer(options, jobStorage);               

            var schedulars = ObjectFactory.GetAllInstances();
            foreach (var schedular in schedulars) {
                schedular.Init();
            }

        }

Schedular Class:

public class Schedular : IJob
{
public void Init()
{

        RecurringJob.AddOrUpdate(() => Clearance.CreateClearance(), Cron.Minutely);
    }
}

You cannot use static RecurringJob.AddOrUpdate method, as it will initialize internal instance of RecurringJobManager on the first call and then use it for all subsequent calls.

You need to manually create a new RecurringJobManager instance on each iteration (passing it the corresponding storage instance), and use its instance methods to schedule jobs.

2 Likes