我需要一个每两周一次的 cron 表达式,由 C# 中的 Cronos nuget 包 进行解释。
每两周一次,我的意思是这样的:每两周的星期一。
我尝试了几种表达方式,但似乎没有任何效果。 我尝试过的一种表达是这样的:
0 0 * * 1/2
这是我测试表达式的代码:
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);
对于 cron 表达式 0 0 * * 1/2,结果是:
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"
有人可以帮我找到一个每两周一次的 cron 表达式吗?
没有办法用简单的 cron 表达式来做到这一点,更好的方法是选择第一周的一天和月中的另一天:
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);
}
输出:
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
您必须使用其他工具来实现您想要的功能。