简体   繁体   中英

How to get Hangfire job scheduler to stagger my 20 minute interval jobs

I have a number of tasks that i need run every 20 minutes. I can achieve this in Hangfire using the cron expression RecurringJob.AddOrUpdate(() => /* my method */, "*/20 * * * *")

The problem with this is, all my tasks will end up running at exactly the same time eg 00:00, 00:20, 00:40, 01:00

Does anyone know of a way to stagger one's 20 minute interval tasks without implementing some sort of manual intervention?

I'd just like Hangfire to run the jobs every 20 minutes from the time I create them, nothing too special :)

I'd try this: First, modify your add or update to specify a job id:

RecurringJob.AddOrUpdate("some-id", () => /* my method */, "*/20 * * * *");

followed by

RecurringJob.Trigger("some-id");

To run a recurring job now, call the Trigger method.

UPDATE: How about a delayed job then instead of a recurring job? Your "my method" creates a new delayed job at the end (Recursion), set to run after 20 mins. You will still use the Trigger method for the first run.

One 'hacky' way of achieving this is to set a small number of workers .

app.UseHangfire(config =>
{
    config.UseServer(2);
});

// or
var server = new BackgroundJobServer(2);

Whether you look at this and say 'oh great!' or 'that is a terrible idea' will depend completely on your own usage of Hangfire. If you only run a few things an hour, or every 15 minutes and you find they're 'treading' on each other then this could be a simple solution.

A second way: You could make an async Task and run await Task.Delay(TimeSpan.FromSeconds(10)) to make a short delay. This quite likely could cause your app to shutdown more slowly because it would think you're still running tasks. So I only only using this in an emergency, or if you're ok with the consequences.

Hopefully Hangfire will support this in a more organized way at some point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM