Search code examples
c#asp.net-corebackground-processhangfire

Hangfire recurring job every certain number of days greater than 31


I would like to use Hangfire to execute a method every certain number of days (specified in my configuration). The problem is that the number of days can be greater than 31, and from what I’ve seen, cron expressions do not support a range greater than this for the interval of days.

Is there another way to approach a case like this? Or should I consider using something else instead of Hangfire?

I have tried Cron.DayInterval(interval) and $"0 0 */{interval} * *" but when the interval is greater than 31 I get an exception: CRON expression is invalid.

I also have tried something like:

if (interval <= 31)
{
    return $"0 0 */{interval} * *";
}
else
{
    int months = interval / 30;
    return $"0 0 * */{months} *";
}

But this is not what I really need.


Solution

  • Hangfire uses cron expressions under the hood. For example, the (deprecated) Cron.DayInterval(int interval) method expands to $"0 0 */{interval} * * which means "run every (interval)" days.

    Since the "day" field of cron expressions cannot exceed 31, you cannot schedule your desired interval.

    It's unfortunate that Hangfire doesn't expose any customization points for scheduling jobs.

    So my suggestion is this:

    Schedule your job to run every day. When the job starts, it performs some check to see if it should actually run.

    For example, if you want to run every 32 days, then you can compute which days of the year that actually corresponds to (depending on your start date). Then you could check against the current date time.

    Example 2: Keep track of the last time the job ran in a database table. When the job starts up, see if the amount of time that has elapsed is greater than or equal to your desired day interval.