Search code examples
c#asp.net-corehangfire

Hangfire not working in asp.net core


enter image description hereI believe, I did set hangfire correctly, but for some reason hangfire adds jobs to Sql Server database but nothing gets executed. I tried everything, but I failed to understand since there is no exception either. I want to run a function from a class which will send emails every week. I have Unit Of Work DI which is injected into controller contructor. The class that will have method to SendEmails needs UnitOfWork DI, I didnt go that far, since I could not make hangfire to print a message on console. Please your help is appreciated. Thank you. My Code is :

//Startup.cs ConfigureServices Method 

 services.AddHangfire(x => x.UseSqlServerStorage("Connection"));

//Configure method 


            app.UseHangfireDashboard();
            app.UseFileServer();
// Controller 
 [Route("api/Hello")]
public class HelloController : Controller
{
    [HttpGet]
    public IActionResult Hello()
    {
        RecurringJob.AddOrUpdate(() => Print(),Cron.MinuteInterval(1));
        return Ok();
    }
    public void Print()
    {

        Console.BackgroundColor =ConsoleColor.Red;
        Console.WriteLine(DateTime.Now);
    }

}

Solution

  • I was missing to add app.UseHangfireServer() I had added this first time then somehow I had removed it while fixing database errors. It seemed to work fine now. I was just wondering if its ok to use "IUnitOfWork unitOfWork" in configure method here.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IUnitOfWork unitOfWork)
    {
        app.UseHangfireDashboard();
        app.UseHangfireServer();
    
        RecurringJob.AddOrUpdate(() => new Job(unitOfWork).Print(), Cron.MinuteInterval(1));
    
        app.UseFileServer();
    }