Skip to content

Commit

Permalink
根据时间步进级别调整时间,解决每月每年时间不固定的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Jul 27, 2024
1 parent 40a2e83 commit 79a3c25
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions XCode/Shards/TimeShardPolicy.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using NewLife;
using XCode.Configuration;
using XCode.Statistics;

namespace XCode.Shards;

Expand All @@ -22,6 +23,9 @@ public class TimeShardPolicy : IShardPolicy
/// <summary>时间区间步进。遇到时间区间需要扫描多张表时的时间步进,默认1天</summary>
public TimeSpan Step { get; set; } = TimeSpan.FromDays(1);

/// <summary>日期级别。年月日</summary>
public StatLevels Level { get; set; }

private readonly String? _fieldName;
#endregion

Expand Down Expand Up @@ -227,14 +231,29 @@ private ShardModel[] GetModels(DateTime start, DateTime end)
{
var models = new List<ShardModel>();

// 猜测时间步进级别
var st = Step;
var level = Level;
if (level <= 0)
{
if (st.TotalDays >= 360)
level = StatLevels.Year;
else if (st.TotalDays >= 28 && st.TotalDays <= 31)
level = StatLevels.Month;
else if (st.TotalDays == 1)
level = StatLevels.Day;
else if (st.TotalHours == 1)
level = StatLevels.Hour;
}

// 根据不仅,把start调整到整点
if (Step.TotalDays >= 1)
if (st.TotalDays >= 1)
start = start.Date;
else if (start.Hour >= 1)
start = start.Date.AddHours(start.Hour);

var hash = new HashSet<String>();
for (var dt = start; dt < end; dt = dt.Add(Step))
for (var dt = start; dt < end;)
{
var model = Shard(dt);
if (model != null)
Expand All @@ -246,6 +265,18 @@ private ShardModel[] GetModels(DateTime start, DateTime end)
hash.Add(key);
}
}

// 根据时间步进级别调整时间,解决每月每年时间不固定的问题
if (level == StatLevels.Year)
dt = dt.AddYears(1);
else if (level == StatLevels.Month)
dt = dt.AddMonths(1);
else if (level == StatLevels.Day)
dt = dt.AddDays(1);
else if (level == StatLevels.Hour)
dt = dt.AddHours(1);
else
dt = dt.Add(st);
}

//// 标准时间区间 start <= @fi < end ,但是要考虑到end有一部分落入新的分片,减一秒判断
Expand Down

0 comments on commit 79a3c25

Please sign in to comment.