Hangfire:如何有条件地安排工作 [英] Hangfire: How to enqueue a job conditionally
问题描述
我正在使用Hangfire触发数据库检索操作作为后台作业.
I am using Hangfire to trigger a database retrieval operation as a background job.
该操作只能执行一次,并且可以通过多种方式触发. (例如,在UI中,每当用户拖放工具时,我都需要在后台启动该作业.但是,如果拖放其他工具,则我不想触发该后台作业,因为它已经从数据库).
This operation is only supposed to happen once, and can be triggered in multiple ways. (for example, in the UI whenever a user drags and drops a tool, I need to fire that job in the background. But if another tool is dragged and dropped, I don't want to fire the background job as it's already prefetched from the database).
这是我的代码现在的样子:
This is what my code looks like now:
var jobId = BackgroundJob.Enqueue<BackgroundModelHelper>( (x) => x.PreFetchBillingByTimePeriods(organizationId) );
我想要的是在执行上述语句之前进行的某种检查,以查找是否已经触发了后台作业;如果是,则不要开火,否则,将其入队.
What I want is some kind of check before I execute above statement, to find if a background job has already been fired; if yes, then do not fire another and if not, then enqueue this .
例如:
bool prefetchIsFired = false;
// find out if a background job has already been fired. If yes, set prefetchIsFired to true.
if (!prefetchIsFired)
var jobId = BackgroundJob.Enqueue<BackgroundModelHelper>( (x) => x.PreFetchBillingByTimePeriods(organizationId, null) );
推荐答案
您可以在作业方法上使用过滤器(DisableMultipleQueuedItemsFilter),如下所示:
You can use a filter (DisableMultipleQueuedItemsFilter) on your job method like here : https://discuss.hangfire.io/t/how-do-i-prevent-creation-of-duplicate-jobs/1222/4
这篇关于Hangfire:如何有条件地安排工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!