Search code examples
c#hangfire.net-7.0

Do hangfire recurring jobs need to be in program.cs?


I am using .Net 7 and Hangfire 1.8.5

Do all of hangfire's recurring jobs have to be listed directly in Program.cs ? Or can I abstract them out into a sub module? I'd rather have 20 recurring jobs in a seperate module than all in Program.cs

Program.cs :

app.UseHangfireDashboard();
app.MapHangfireDashboard();

// Hangfire Recurring Jobs
RecurringJob.AddOrUpdate<MyTestService>("Test Job", (x) => x.testJob("hangfire test 
job"), Cron.Daily(8, 30));
....to infitity...

Could I have instead...

Program.cs :

app.UseHangfireDashboard();
app.MapHangfireDashboard();

BackgroundJobs jobs = new BackgroundJobs();
jobs.MyRecurringJobs();

I assume I'd need to pass something into this new BackgroundJobs class? How would I setup hangfire to work this way?


Solution

  • No, hangfire recurring jobs do not need to be in program.cs. As others have pointed out RecurringJob is a static class and can be called anywhere from your code.

    However if you want to call it in program.cs separately. I would use a static class as below:

    public static class HangfireWorker
    {
      public static void StartRecurringJobs(this IApplicationBuilder app)
      {
       RecurringJob.AddOrUpdate("test_job", () => TestJob("hangfire test job"), 
                Cron.Daily(8, 30));
                        }
            //to infinity
    }
    

    Then in my program.cs proceed to call app.StartRecurringJobs();

    Also incase you face issue jobstorage.Current not initialized on startup you might need to initialize the Jobstorage.Current