-1

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?

Scottish Smile
  • 455
  • 7
  • 22

1 Answers1

1

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

DenisMicheal.k
  • 197
  • 2
  • 12
  • Thanks for the guidance! Every example I'd seen online was using them in program.cs and this reply shows me good standard practice of how to abstract them. – Scottish Smile Sep 02 '23 at 07:09