Search code examples
c#asp.netcroncronexpressionhangfire

Programmatically creating Hangfire cron expression based on user input


I have a C# .NET web application with a UI that looks similar to http://www.cronmaker.com/. The user can select the frequency of a job from many options. I need to be able to create a cron expression to represent the user's desired frequency, and it must be compatible with Hangfire. My ideas were to either:

  1. Find an existing library that does it. But I haven't been able to. I heard that Quartz could do it (though it would be overkill), but it seemed that it could create cron expressions for some cases but not others.

  2. Make my own tool, using cronmaker.com to figure out the format. However, cronmaker creates cron expressions in a format that Hangfire considers invalid. For "every hour," cronmaker says "0 0 0/1 1/1 * ? *" which Hangfire said was invalid. I found that "0 */1 * * *" works.

I need to be able to dynamically generate any cron expression. Surely there's a library out there that can do something like CronLibrary.GetCronExpression(Frequency.EveryNDays, 3, "12:00") with options to cover every conceivable situation. Does anyone know of such a library ?


Solution

  • I didn't find a library, but the site http://crontab.guru/ was tremendously helpful for creating cron expressions that are valid for Hangfire. Using that site as a reference, I was able to write code to map the UI selections to a cron expression and vice versa.