cs-codex-dist-tests/Tools/TestNetRewarder/TimeSegmenter.cs

63 lines
1.9 KiB
C#
Raw Normal View History

2024-01-22 09:27:07 +00:00
using Logging;
using Utils;
namespace TestNetRewarder
{
2024-06-14 09:05:29 +00:00
public interface ITimeSegmentHandler
{
Task OnNewSegment(TimeRange timeRange);
}
2024-01-22 09:27:07 +00:00
public class TimeSegmenter
{
private readonly ILog log;
2024-06-14 09:05:29 +00:00
private readonly ITimeSegmentHandler handler;
2024-01-22 09:27:07 +00:00
private readonly TimeSpan segmentSize;
2024-06-14 09:05:29 +00:00
private DateTime latest;
2024-01-22 09:27:07 +00:00
2024-06-14 09:05:29 +00:00
public TimeSegmenter(ILog log, Configuration configuration, ITimeSegmentHandler handler)
2024-01-22 09:27:07 +00:00
{
this.log = log;
2024-06-14 09:05:29 +00:00
this.handler = handler;
2024-04-07 12:04:31 +00:00
if (configuration.IntervalMinutes < 0) configuration.IntervalMinutes = 1;
2024-01-22 10:47:28 +00:00
2024-04-07 12:04:31 +00:00
segmentSize = configuration.Interval;
2024-06-14 09:05:29 +00:00
latest = configuration.HistoryStartUtc;
2024-01-22 09:27:07 +00:00
2024-06-14 09:05:29 +00:00
log.Log("Starting time segments at " + latest);
2024-01-22 09:27:07 +00:00
log.Log("Segment size: " + Time.FormatDuration(segmentSize));
}
2024-06-14 09:05:29 +00:00
public async Task ProcessNextSegment()
2024-01-22 09:27:07 +00:00
{
2024-06-14 09:05:29 +00:00
var end = latest + segmentSize;
var waited = await WaitUntilTimeSegmentInPast(end);
2024-01-22 09:27:07 +00:00
if (Program.CancellationToken.IsCancellationRequested) return;
2024-01-22 10:47:28 +00:00
var postfix = "(Catching up...)";
if (waited) postfix = "(Real-time)";
2024-06-14 09:05:29 +00:00
log.Log($"Time segment [{latest} to {end}] {postfix}");
var range = new TimeRange(latest, end);
latest = end;
2024-01-22 10:47:28 +00:00
2024-06-14 09:05:29 +00:00
await handler.OnNewSegment(range);
}
private async Task<bool> WaitUntilTimeSegmentInPast(DateTime end)
{
await Task.Delay(TimeSpan.FromSeconds(3), Program.CancellationToken);
2024-01-22 09:27:07 +00:00
2024-06-14 09:05:29 +00:00
var now = DateTime.UtcNow;
while (end > now)
{
var delay = (end - now) + TimeSpan.FromSeconds(3);
await Task.Delay(delay, Program.CancellationToken);
return true;
}
return false;
2024-01-22 09:27:07 +00:00
}
}
}