Skip to content

Instantly share code, notes, and snippets.

@code-atom
Created October 7, 2016 11:20
Show Gist options
  • Save code-atom/9836ffd5f73b0089e5df8d56804decd6 to your computer and use it in GitHub Desktop.
Save code-atom/9836ffd5f73b0089e5df8d56804decd6 to your computer and use it in GitHub Desktop.
Cron to Quartz parser
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WhoGroup.Schedulers
{
internal static class SchedulerHelper
{
public static string GernerateQUARTZExpression(string cronExpression)
{
var splitExpression = cronExpression.Split(' ').ToArray();
var quartzExpression = new List<String>();
quartzExpression.Add("0");
var toggleQuartzCompat = false;
for(int index = 0; index < splitExpression.Length; index++)
{
var item = splitExpression[index];
// index 0 = minutes
// index 1 = hours
// these cron definitions should be compatible with quartz so we push them as is
if (index == 0 || index == 1) {
quartzExpression.Add(item);
}
// index 2 = DOM = Day of Month
if (index == 2) {
if (item != "?") {
toggleQuartzCompat = true;
}
if (item == "*") {
toggleQuartzCompat = false;
item = "?";
}
quartzExpression.Add(item);
}
// index 3 = Month
if (index == 3) {
quartzExpression.Add(item);
}
// index 4 = DOW = Day of Week
if (index == 4) {
// day of week needs another adjustments - it is specified as 1-7 in quartz but 0-6 in crontab
var itemAbbreviated = AdvanceNumber(item);
if (toggleQuartzCompat == true) {
quartzExpression.Add("?");
} else {
quartzExpression.Add(itemAbbreviated);
}
}
}
quartzExpression.Add("*");
return String.Join(" ", quartzExpression.ToArray());
}
private static string AdvanceNumber(string str)
{
var quartzCompatibleStr = "";
int num;
Array.ForEach(str.Split('\0'), chr =>{
if (int.TryParse(chr, out num))
{
quartzCompatibleStr += num+1;
} else {
quartzCompatibleStr += chr;
}
});
return quartzCompatibleStr;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment