Search code examples
c#.netcron

Biweekly (every two weeks) cron expression interpreted by Cronos library


I need a biweekly cron expression to be interpreted by Cronos nuget package in C#.

By biweekly I mean something like this: Every 2 weeks on Monday.

I tried several expressions, but nothing seems to work. One expression that I tried is this one:

0 0 * * 1/2

and this is my code to test the expression:

DateTime startDate = new DateTime(DateTime.Now.Year, 8, 1, 0, 0, 0, DateTimeKind.Utc);

// Convert the cron expression to a CronExpression instance
var cron = CronExpression.Parse("0 0 * * 1/2");

// Get the next occurrences
var nextOccurrence = cron.GetNextOccurrence(startDate);
var nextOccurrence2 = cron.GetNextOccurrence(nextOccurrence.Value);
var nextOccurrence3 = cron.GetNextOccurrence(nextOccurrence2.Value);
var nextOccurrence4 = cron.GetNextOccurrence(nextOccurrence3.Value);

And the result, for the cron expression 0 0 * * 1/2 is:

nextOccurrence.Value.ToString()
"8/2/2023 12:00:00 AM"
nextOccurrence2.Value.ToString()
"8/4/2023 12:00:00 AM"
nextOccurrence3.Value.ToString()
"8/6/2023 12:00:00 AM"
nextOccurrence4.Value.ToString()
"8/7/2023 12:00:00 AM"

Could someone help me find a biweekly cron expression?


Solution

  • There is no way to do this with a simple cron expression, the better you can do is select one day on first week and another day in the middle of the month:

    using Cronos;
    
    DateTime startDate = new DateTime(DateTime.Now.Year, 8, 1, 0, 0, 0, DateTimeKind.Utc);
    
    // Convert the cron expression to a CronExpression instance
    var cron = CronExpression.Parse("0 0 1-6,15-20 * 1");
    
    // next year's ocurrences
    var nextOccurrence = cron.GetNextOccurrence(startDate);
    Console.WriteLine(nextOccurrence);
    for (int i = 0; i < 11; i++)
    {
        nextOccurrence = cron.GetNextOccurrence(nextOccurrence.Value);
        Console.WriteLine(nextOccurrence);
    }
    

    Output:

    9/4/2023 12:00:00 AM
    9/18/2023 12:00:00 AM
    10/2/2023 12:00:00 AM
    10/16/2023 12:00:00 AM
    11/6/2023 12:00:00 AM
    11/20/2023 12:00:00 AM
    12/4/2023 12:00:00 AM
    12/18/2023 12:00:00 AM
    1/1/2024 12:00:00 AM
    1/15/2024 12:00:00 AM
    2/5/2024 12:00:00 AM
    2/19/2024 12:00:00 AM
    

    You have to use another tool for what you want.