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

Feature request: Method for checking if now is a valid occurance #58

Closed Pandetthe closed 11 months ago

Pandetthe commented 1 year ago

Hi, I am working on a small project for scheduling custom scripts from db. I was trying to check if DateTime.UtcNow is a valid occurance, but I came across the lack of such an option. I think it could be a good feature.

odinserj commented 1 year ago

You can use something like the following extension method. The main thing is to normalize the given value to ignore everything less than 1 second – milliseconds, ticks. Otherwise it would be very hard to find a matching value.

public static class CronExpressionExtensions
{
    public static bool IsMatch(this CronExpression expression, DateTime utcNow)
    {
        if (expression == null) throw new ArgumentNullException(nameof(expression));
        if (utcNow.Kind != DateTimeKind.Utc) throw new ArgumentException("Should be of DateTimeKind.Utc", nameof(utcNow));

        var normalized = new DateTime(
            utcNow.Year, utcNow.Month, utcNow.Day,
            utcNow.Hour, utcNow.Minute, utcNow.Second,
            DateTimeKind.Utc);

        return expression.GetNextOccurrence(normalized, inclusive: true) == normalized;
    }
}
Pandetthe commented 11 months ago

Thank you very much