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

∥☆過路亽.° 提交于 2020-06-09 02:55:53

问题


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 configuration were working fine, I just wrote a very simple recurring job, aimed to print the current DateTime on the console output :

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

The weird thing is that every minute, it prints the same message, corresponding to the date and time of the first time the message was printed, and not updating the DateTime.Now part.

If I access the /Hangfire dashboard, and look at the job details, it appears translated as static datetime output, as such :

Console.WriteLine("15/09/2017 15:27:21");

So the job seems to be kind of 'compiled' when enqueued and this is obviously not what I intended to do.

I tried to replace this job by a job counting rows on a database table. And the problem is the same : if I add or remove rows between two occurences of the job, the row count displayed is not updated. Update only occurs if I restart the web application.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/46240864/hangfire-in-asp-net-core-simple-recurring-job-does-not-refresh-its-dynamic-con

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!