Hangfire in ASP.Net Core : simple recurring job does not refresh its dynamic content

前端 未结 2 660
臣服心动
臣服心动 2021-01-25 14:49

I am trying to implement cron task on a web application in ASP.Net Core 1.1.

I decided to choose the Hangfire library.

In order to check if my installation and c

相关标签:
2条回答
  • 2021-01-25 15:11

    So your problem is that Hangfire serializes the arguments you send to the job using NewtonSoft. When your program enqueues the job, it gets the current time, and then will call that function with that time.

    Try moving the function into a method call. So instead of

    RecurringJob.AddOrUpdate(() => Console.WriteLine($"{DateTime.Now}"), Cron.Minutely);  
    

    Try

    RecurringJob.AddOrUpdate(() => PrintTime(), Cron.Minutely); 
    ...
    private static void PrintTime() {
        Console.WriteLine($"{DateTime.Now}");
    }
    

    If my understanding of Hangfire is correct, this will only serialize the name of the method to call, but not serialize the time.

    0 讨论(0)
  • 2021-01-25 15:30

    For the issue described in my question, Stephen Vernyi has spotted the issue : since Hangfire serializes parameters in JSON, the first datetime was frozen when serialized, so that each subsequent execution would provide the same output.

    But one must be careful when writing a method, as he suggested.

    Since I was casually trying to have this all work, all my tests where written within a static class with static methods. And such implementation had provided the same frozen datetime issue !

    When I decided to refactor my implementation, with Job services, registered in the default ASP.Net Core IoC container, and set up to provide new service instances at every request, it not only solved the frozen output issue, but also every issue encountered with Dependency injections.

    0 讨论(0)
提交回复
热议问题