简体   繁体   中英

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

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));
}

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM