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

54 lines
1.9 KiB
C#
Raw Normal View History

2024-01-22 09:27:07 +00:00
using Logging;
using Utils;
namespace TestNetRewarder
{
public class TimeSegmenter
{
private readonly ILog log;
private readonly TimeSpan segmentSize;
private DateTime start;
public TimeSegmenter(ILog log, Configuration configuration)
{
this.log = log;
2024-04-07 12:04:31 +00:00
if (configuration.IntervalMinutes < 0) configuration.IntervalMinutes = 1;
2024-01-22 10:47:28 +00:00
if (configuration.CheckHistoryTimestamp == 0) throw new Exception("'check-history' unix timestamp is required. Set it to the start/launch moment of the testnet.");
2024-04-07 12:04:31 +00:00
segmentSize = configuration.Interval;
2024-01-22 10:47:28 +00:00
start = DateTimeOffset.FromUnixTimeSeconds(configuration.CheckHistoryTimestamp).UtcDateTime;
2024-01-22 09:27:07 +00:00
log.Log("Starting time segments at " + start);
log.Log("Segment size: " + Time.FormatDuration(segmentSize));
}
public async Task WaitForNextSegment(Func<TimeRange, Task> onSegment)
{
var now = DateTime.UtcNow;
var end = start + segmentSize;
2024-01-22 10:47:28 +00:00
var waited = false;
2024-01-22 09:27:07 +00:00
if (end > now)
{
// Wait for the entire time segment to be in the past.
2024-04-01 11:56:07 +00:00
var delay = end - now;
2024-01-22 10:47:28 +00:00
waited = true;
2024-02-19 13:56:49 +00:00
log.Log($"Waiting till time segment is in the past... {Time.FormatDuration(delay)}");
2024-01-22 09:27:07 +00:00
await Task.Delay(delay, Program.CancellationToken);
}
2024-04-01 11:56:07 +00:00
await Task.Delay(TimeSpan.FromSeconds(3), Program.CancellationToken);
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)";
log.Log($"Time segment [{start} to {end}] {postfix}");
2024-01-22 09:27:07 +00:00
var range = new TimeRange(start, end);
start = end;
await onSegment(range);
}
}
}