'How to create a cron like job using HangFire at startup?

I have a service class that has a method like

public void BackgroundJob(string cronrule)
{
    RecurringJob.AddOrUpdate("somejob", () => FetchCallHistoryAsync(), cronrule);
}

I want to put start the job in the startup, something like this

public void ConfigureServices(IServiceCollection services)
{
    ...
    new MyClass().BackgroundJob("10 * * * *")
}

But my class depends on several other services, I don't know how to instantiate it from Startup.cs, any idea?



Solution 1:[1]

Okay I found a way

For any cases that you need to instantiate a service at startup, you register it at ConfigureServices(IServiceCollection services) and then inject it in Configure(YourService yserv)

For my special case I created a CrontabService

namespace MyApp
{
    public class CrontabService
    {
        private DependentService D;
        public CrontabService(DependentService d)
        {
              D = d
        }

        public Start()
        {
              RecurringJob.AddOrUpdate("some-id", () => D.Job(), "*/15 * * * *");
        }
    }
}

This way all my crontab jobs stay on the same service.

Then I start it at Startup.cs::Configure

// Startup.cs
     public void ConfigureServices(IServiceCollection services)
     {
         ...
         services.AddSingleton<DepedentService>();
         services.AddSingleton<CrontabService>();
      }
...
     public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider, CrontabService cron)
     {
          ...
          cron.Start();
          ...
     }
...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1