关于Hangfire定时任务在指定时段内按不同间隔执行的Cron表达式配置需求咨询
Got it, let's tackle your two Hangfire scheduling needs step by step with the right Cron expressions and practical code snippets:
The correct Cron expression for this requirement is:
0 12-21 * * *
Breakdown of the Cron fields (order: minute, hour, day, month, weekday):
0: Triggers exactly on the 0th minute of each hour (on-the-hour execution)12-21: Restricts runs to hours 12 (noon) through 21 (9 PM)*: Runs every day*: Runs every month*: Runs on any weekday
To set this up in Hangfire, use the RecurringJob API like this:
// Replace `YourJobMethod()` with your actual task implementation RecurringJob.AddOrUpdate( "hourly-daily-job", () => YourJobMethod(), "0 12-21 * * *", TimeZoneInfo.Local // Optional: Specify your local time zone if needed (Hangfire uses UTC by default) );
Since you want runs at 12:05, 14:05, 16:05, 18:05, 20:05 (stopping before the 21:00 cutoff), you can use either of these two equivalent Cron expressions:
Option 1 (explicit hour list for clarity):
5 12,14,16,18,20 * * *
Option 2 (range with step for brevity):
5 12-20/2 * * *
Breakdown:
5: Triggers at the 5th minute of the target hours12,14,16,18,20/12-20/2: Targets every 2 hours starting at 12, up to 20 (since 20+2=22 falls outside your 21:00 window)*: Runs every day*: Runs every month*: Runs on any weekday
Hangfire configuration example using the range-with-step expression:
RecurringJob.AddOrUpdate( "every-2hours-daily-job", () => YourJobMethod(), "5 12-20/2 * * *", TimeZoneInfo.Local );
Just a quick note: Double-check your server's time zone vs. the schedule you need—Hangfire uses UTC by default, so specifying your local time zone ensures the runs align with your intended daily window.
内容的提问来源于stack exchange,提问作者Baskar Lakshmi

