Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NCrontab demo showing direct use of CrontabField
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ncrontab" Version="3.3.1" />
</ItemGroup>
</Project>
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using NCrontab;
// See also: https://github.com/atifaziz/NCrontab/issues/71
static class Program
{
static readonly (CrontabFieldKind Kind, Func<string, CrontabField> Parser)[] CrontabFields =
{
(CrontabFieldKind.Second , CrontabField.Seconds ),
(CrontabFieldKind.Minute , CrontabField.Minutes ),
(CrontabFieldKind.Hour , CrontabField.Hours ),
(CrontabFieldKind.Day , CrontabField.Days ),
(CrontabFieldKind.Month , CrontabField.Months ),
(CrontabFieldKind.DayOfWeek, CrontabField.DaysOfWeek),
};
static void Main(string[] args)
{
if (args.Length == 0)
throw new Exception("Missing crontab expression argument.");
var expressions = args[0].Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (expressions.Length < 5 || expressions.Length > 6)
throw new Exception("Invalid crontab expression field count (must be 5 or 6).");
foreach (var (expr, (kind, parser)) in
expressions.Zip(CrontabFields.TakeLast(expressions.Length)))
{
var field = parser(expr);
Console.WriteLine($"{expr} : {kind} = {string.Join(", ", field.Values())}");
}
}
static IEnumerable<int> Values(this ICrontabField field)
{
for (var n = field.GetFirst(); n >= 0; n = field.Next(n + 1))
yield return n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment