Hangfire: How to enqueue a job conditionally

2019-09-07 06:41发布

I am using Hangfire to trigger a database retrieval operation as a background job.

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 .

for example:

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

标签: hangfire
1条回答
疯言疯语
2楼-- · 2019-09-07 07:07

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

查看更多
登录 后发表回答