HangfireIO / Cronos

A fully-featured .NET library for working with Cron expressions. Built with time zones in mind and intuitively handles daylight saving time transitions
MIT License
974 stars 114 forks source link

GetNextOccurrence based on today's date #44

Open jerkohren opened 2 years ago

jerkohren commented 2 years ago

Hi. I have a problem getting next occurrence time or i just miss something in Cronos documentation.

Problem: User can set scheduler, which is done with the cron expression. User can set date and time and interval. For example 1.2.2012 15:00:00 every two days. But the date doesn't change often, only when user set new time or interval, what means if today is 20.2.2012 12:00:00, then GetNextOccurrence() get the 3.2.2012 15:00:00 as result, but i want to get 21.2.2012, which is the next relevant run time. Workaround:

var occs = expression.GetOccurrences(schedule.Time, DateTime.UtcNow, TimeZoneInfo.Local).ToList();
job.NextRunTime = expression.GetNextOccurrence(occs.Last(), TimeZoneInfo.Local);

I just get all occurrences till today and then i use last one to get the ACTUAL next one.

Does it make sense to have a function like: GetNextOccurrenceBasedOnDateTimeNow(...)?

Thank You

jbennink commented 1 year ago

Probably a stale issue but anyways:

So schedule.Time is that user entered initial start date and the cron expression is something like 0 0 */2 * * In that case when you use GetNextOccurrence() you will have to supply the last occurrence as input parameter to get the next occurrence. Th first time, ie. when the user sets this up you use the schedule.Time as last occurrence and the next one is calculated. You could then store that occurrence in schedule.Time, unles you want to keep that value, in that case you will have to store it in another variable/field. Your workaround also solves this but, as you stated, in a sub-optimal way.

I don't think this is a bug, it's just the way cron works, you supply it a starting point date and a cron expression and it calculates the next occurrence according to the cron expression.

FaithfulDev commented 7 months ago

It's a few years later, so now it's definitely stale 😅 but...

If I understand this correctly, you want a method that acts as a shortcut for expression.GetNextOccurrence(DateTime.UtcNow, TimeZoneInfo.Local);?

Having a dedicated method for this is a bit overkill IMO. If you want the current date, just supply the current date.