我正在一个可以创建重复任务的任务系统上工作,在某些情况下,我需要帮助来弄清楚:
我正在使用this library来确定何时创建任务并计划在接下来的28天内花费的时间。例如,每天9点:
CronExpression expression = CronExpression.Parse("0 9 * * *");
但是阅读有关Cronos表达式的信息后,我仍然不知道如何获得一个每3周重复一次的表达式。一周中的哪几天可以,但是每隔x周我都找不到。
能帮我吗? 谢谢
答案 0 :(得分:0)
我不认为您可以按周安排cron,请参见下文: 我建议将同一份工作安排在一个月的不同日期。
┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of the month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
│ │ │ │ │ 7 is also Sunday on some systems)
│ │ │ │ │
│ │ │ │ │
* * * * * command to execute
答案 1 :(得分:0)
无法使用cron表达式执行此操作。就我而言,我需要这些事件来进行一些成本计算。这是我做的似乎运行良好的功能:
public List<DateTime> GetOccurrencesInWeeksInterval(DateTime start, DateTime end)
{
var ret = new List<DateTime>();
DateTime? lastDate = null;
int weekInterval = _rptConfig.Interval;
CronExpression expression = CronExpression.Parse(this.GetCronExpression()); // this would return something like "0 9 * * 1,3,5"
var dates = expression.GetOccurrences(start, end).ToList();
if (weekInterval == 1) {
return dates;
}
if (dates.Any())
{
foreach (var date in dates)
{
if (lastDate == null)
{
ret.Add(date);
lastDate = date;
}
else
{
var weekDiff = HelperFunctions.GetWeekDiff(lastDate.Value, date);
if (weekDiff == 0)
{
ret.Add(date);
}
else if (weekDiff > 0 && (weekDiff % weekInterval) == 0)
{
ret.Add(date);
}
}
}
}
return ret;
}
这是GetWeekDiff
函数:
/// <summary>
/// https://stackoverflow.com/questions/49924085/week-difference-between-2-dates-in-c-sharp#49924454
/// </summary>
/// <param name="dtStart"></param>
/// <param name="dtEnd"></param>
/// <returns></returns>
public static int GetWeekDiff(DateTime dtStart, DateTime dtEnd, DayOfWeek startOfWeek = DayOfWeek.Monday) {
//===============================================
var diff = dtEnd.Subtract(dtStart);
var weeks = (int)diff.Days / 7;
// need to check if there's an extra week to count
var remainingDays = diff.Days % 7;
var cal = CultureInfo.InvariantCulture.Calendar;
var d1WeekNo = cal.GetWeekOfYear(dtStart, CalendarWeekRule.FirstFullWeek, startOfWeek);
var d1PlusRemainingWeekNo = cal.GetWeekOfYear(dtStart.AddDays(remainingDays), CalendarWeekRule.FirstFullWeek, startOfWeek);
if (d1WeekNo != d1PlusRemainingWeekNo)
weeks++;
return weeks;
}
希望这对某人有帮助,因为我意识到这是一个非常普遍的问题。