atifaziz / NCrontab

Crontab for .NET

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Implement equality for 'ContrabSchedule'

julealgon opened this issue · comments

There is currently no way to check a ContrabSchedule object for equality against another schedule. It's also not possible to properly implement a custom EqualityComparer from the outside since the fields that store the data inside the schedule are all private.

This could be fixed by implementing IEquatable<ContrabSchedule> on the model.

I'll think about this but meanwhile…

There is currently no way to check a ContrabSchedule object for equality against another schedule.

The ToString() implementation of ContrabSchedule returns an expanded/lowered version of the one originally parsed expression:

/// <summary>
/// Returns a string in crontab expression (expanded) that represents
/// this schedule.
/// </summary>
public override string ToString()
{
var writer = new StringWriter(CultureInfo.InvariantCulture);
if (_seconds != null)
{
_seconds.Format(writer, true);
writer.Write(' ');
}
_minutes.Format(writer, true); writer.Write(' ');
_hours.Format(writer, true); writer.Write(' ');
_days.Format(writer, true); writer.Write(' ');
_months.Format(writer, true); writer.Write(' ');
_daysOfWeek.Format(writer, true);
return writer.ToString();
}

It can be used today as a good basis for equality comparison via an IEqualityComparer<CrontabSchedule> implementation like so:

sealed class EqualityComparer<CrontabSchedule> : IEqualityComparer<CrontabSchedule>
{
    public bool Equals(CrontabSchedule x, CrontabSchedule y) =>
        x?.ToString() == y?.ToString();

    public int GetHashCode(CrontabSchedule obj) =>
        obj.ToString().GetHashCode();
}

Usage would then be:

var comparer = new EqualityComparer<CrontabSchedule>();
var schedule1 = CrontabSchedule.Parse("0-59 * * * Mon-Fri/2");
var schedule2 = CrontabSchedule.Parse("* * * * Fri,Mon,Wed");
var schedule3 = CrontabSchedule.Parse("* * * * *");
Console.WriteLine(comparer.Equals(schedule1, schedule2)); // True
Console.WriteLine(comparer.Equals(schedule1, schedule3)); // False
Console.WriteLine(comparer.Equals(schedule2, schedule3)); // False

Note how 0-59 * * * Mon-Fri/2 (schedule1) and * * * * Fri,Mon,Wed (schedule2) compare equal even though they are expressed differently.