Hangfire job not firing when called inside of ASP.NET MVC Action method

1.5k Views Asked by At

The hangfire job does not start when putting it inside of an Index method in MVC. I can't figure out why.

[HttpGet]
public IActionResult Index()
{
     RecurringJob.AddOrUpdate(() => GetCurrentUserNotifications(User.Identity.Name), Cron.MinuteInterval(1));

      return View(vm);
}

public void GetCurrentUserNotifications(string userId)
{

    _connectionManager.GetHubContext<NotificationsHub>()
        .Clients.All.broadcastNotifications(_repository.GetNotifications()
        .Where(x => x.DateTime <= DateTime.Now && x.CreatedBy == userId));
}
1

There are 1 best solutions below

0
On BEST ANSWER

The problem is your method GetCurrentUserNotifications(string userId) is a method of your controller class. When Hangfire execute the job, it will try to create an instance of your controller class. But I believe your controller class does not have a parameter less constructor. So it will fail to execute the job. The solution is to create a separate class, for example BackgroundProcess. Put your GetCurrentUserNotifications in to it, and call like below:

RecurringJob.AddOrUpdate(() => new BackgroundProcess().GetCurrentUserNotifications(User.Identity.Name), Cron.MinuteInterval(1));