ASP.Net Core中的Hangfire:简单的重复作业不会刷新其动态内容 [英] Hangfire in ASP.Net Core : simple recurring job does not refresh its dynamic content

查看:344
本文介绍了ASP.Net Core中的Hangfire:简单的重复作业不会刷新其动态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ASP.Net Core 1.1中的Web应用程序上实现cron任务.

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

我决定选择 Hangfire 库.

为了检查我的安装和配置是否正常,我写了一个非常简单的重复作业,目的是在控制台输出上打印当前的DateTime:

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

奇怪的是,它每分钟都会打印相同的消息,与第一次打印该消息的日期和时间相对应,而不会更新DateTime.Now部分.

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.

如果我访问/Hangfire仪表板,并查看作业详细信息,它将显示为静态日期时间输出,例如:

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.

我试图通过对数据库表中的行进行计数的作业来代替此作业.问题是相同的:如果我在两次作业之间添加或删除行,则显示的行数不会更新.仅当我重新启动Web应用程序时才会发生更新.

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.

推荐答案

因此,您的问题是Hangfire使用NewtonSoft序列化了发送给作业的参数.当您的程序将作业排入队列时,它将获取当前时间,然后在该时间调用该函数.

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

尝试

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

如果我对Hangfire的理解是正确的,那么这只会序列化要调用的方法的名称,而不会序列化时间.

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

这篇关于ASP.Net Core中的Hangfire:简单的重复作业不会刷新其动态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆