Search code examples
c#asp.net-core.net-corehangfire

How to running a DateTime-based Recurring Job Using Hangfire?


I'm using Hangfire in an ASP.NET Core app. I want to run a job like this: () => Console.WriteLine($"Triggered At {DateTime.Now.ToString()} !!") every minute. I expect to get this result:

Triggered At 5/16/2020 3:05:40 PM
Triggered At 5/16/2020 3:06:40 PM
Triggered At 5/16/2020 3:07:40 PM
Triggered At 5/16/2020 3:08:40 PM

but I get the result as follow:

Triggered At 5/16/2020 3:05:40 PM
Triggered At 5/16/2020 3:05:40 PM
Triggered At 5/16/2020 3:05:40 PM
Triggered At 5/16/2020 3:05:40 PM

I have used this code:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    ...
    ...
    app.UseHangfireDashboard();

    RecurringJob.AddOrUpdate("TestJob",
        () => Console.WriteLine($"Triggered At {DateTime.Now.ToString()} !!"), "* * * * *");

    app.UseMvc();
}

Where am I going wrong?

Thanks


Solution

  • I think you should wrap it inside a method.

    Hangfire serializes arguments

    public static void Method() {
       Console.WriteLine($"Triggered At {DateTime.Now.ToString()} !!");
    }
    
     RecurringJob.AddOrUpdate("TestJob",
            () => Method(), "* * * * *");