Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ Import-Module ./scripts/PSBuild.psm1
- The library prevents overlapping executions - if an action is still running when the next interval arrives, it waits until the current action completes
- `LastRunTimestamp` (a `Stopwatch` timestamp) tracks when the action last executed (based on `IntervalType`), and is what scheduling measures from. `LastRunTime` records the same moment as wall-clock time for reporting only: the wall clock can be set back, which would hold the action off for as long as it moved
- A run is due once `ActionInterval` has passed (`>=`), and a `FromLastStart` run is stamped with the clock reading its tick judged it due at, not when the thread pool started it. The polling wait tops `Task.Delay` up to the full `PollingInterval`, because timers can wake a tick early. Without all three, equal polling and action intervals regularly skip a tick
- `ChangeInterval(TimeSpan)` replaces `ActionInterval` under the lock while polling runs; the next poll measures it from the kept `LastRunTimestamp`
- `Stop()` cancels the async action's token on the thread pool (`CancelAction`), never inline, so token callbacks and the cleanup they resume cannot block or deadlock the caller (#83). A callback that throws is kept in `CancellationFailure` for `RethrowExceptions`
- Polling can be stopped/restarted via `Stop()`/`StopAsync()` and `Restart()`/`RestartAsync()`. A dispatched run re-checks `StopGeneration` under the lock before it begins, so `Stop()` skips one that has not started; `StopAsync()` also waits for the polling loop and any run in progress
- The class is sealed and implements `IDisposable`. `Dispose()` stops like `Stop()` and marks the instance disposed, so `Restart()`/`RestartAsync()` throw `ObjectDisposedException`. The polling loop roots the instance, so an instance that is neither stopped nor disposed runs for the life of the process
Expand Down
62 changes: 62 additions & 0 deletions IntervalAction.Test/IntervalActionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
{
Interlocked.Increment(ref executions);
// Simulate a long running task.
Thread.Sleep(500);

Check warning on line 55 in IntervalAction.Test/IntervalActionTests.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Do not use 'Thread.Sleep()' in a test.

Check warning on line 55 in IntervalAction.Test/IntervalActionTests.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Do not use 'Thread.Sleep()' in a test.
},
IntervalType = IntervalType.FromLastStart
};
Expand Down Expand Up @@ -1401,6 +1401,68 @@
Assert.IsTrue(intervalAction.TryRun(), "Expected a tick that lands exactly on the interval to run the action, not wait for the next tick.");
}

[TestMethod]
[DataRow(IntervalType.FromLastCompletion)]
[DataRow(IntervalType.FromLastStart)]
public void ChangeIntervalAppliesToTheNextPollMeasuredFromTheLastRun(IntervalType intervalType)
{
IntervalAction intervalAction = StartIdle(intervalType, out TimeSpan actionInterval);

const long lastRun = 1_000_000;
long intervalTicks = (long)(actionInterval.TotalSeconds * Stopwatch.Frequency);
intervalAction.LastRunTimestamp = lastRun;
intervalAction.GetTimestamp = () => lastRun + (intervalTicks / 2);

Assert.IsFalse(intervalAction.TryRun(), "Expected the run not to be due halfway through the original interval.");

intervalAction.ChangeInterval(actionInterval / 4);
Assert.IsTrue(intervalAction.TryRun(), "Expected a shorter interval that has already passed since the last run to make the run due.");
}

[TestMethod]
public void ChangeIntervalToALongerIntervalHoldsOffARunThatWasDue()
{
IntervalAction intervalAction = StartIdle(IntervalType.FromLastCompletion, out TimeSpan actionInterval);

const long lastRun = 1_000_000;
long intervalTicks = (long)(actionInterval.TotalSeconds * Stopwatch.Frequency);
intervalAction.LastRunTimestamp = lastRun;
intervalAction.GetTimestamp = () => lastRun + intervalTicks;

intervalAction.ChangeInterval(actionInterval * 2);
Assert.IsFalse(intervalAction.TryRun(), "Expected the longer interval to hold off a run the original interval had made due.");
}

[TestMethod]
public async Task ChangeIntervalSpeedsUpARunningAction()
{
int counter = 0;
using IntervalAction intervalAction = IntervalAction.Start(new()
{
PollingInterval = TimeSpan.FromMilliseconds(20),
ActionInterval = TimeSpan.FromHours(1),
Action = () => Interlocked.Increment(ref counter),
});

// The first run is due at once. After it, an hour-long interval would hold off every other.
Stopwatch stopwatch = Stopwatch.StartNew();
while (Volatile.Read(ref counter) < 1 && stopwatch.Elapsed < TimeSpan.FromSeconds(10))
{
await Task.Delay(10).ConfigureAwait(false);

Check warning on line 1451 in IntervalAction.Test/IntervalActionTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_IntervalAction&issues=AaHPxdvID1hutzVoGb4H&open=AaHPxdvID1hutzVoGb4H&pullRequest=109
}

intervalAction.ChangeInterval(TimeSpan.FromMilliseconds(20));

while (Volatile.Read(ref counter) < 3 && stopwatch.Elapsed < TimeSpan.FromSeconds(10))
{
await Task.Delay(10).ConfigureAwait(false);

Check warning on line 1458 in IntervalAction.Test/IntervalActionTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Consider using the overload that accepts a CancellationToken and pass 'TestContext.CancellationToken'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_IntervalAction&issues=AaHPxdvID1hutzVoGb4I&open=AaHPxdvID1hutzVoGb4I&pullRequest=109
}

await intervalAction.StopAsync().ConfigureAwait(false);
Assert.IsGreaterThanOrEqualTo(3, counter, $"Expected the shorter interval to take effect while running, but the action ran {counter} time(s).");
intervalAction.RethrowExceptions();
}

[TestMethod]
[DataRow(IntervalType.FromLastStart, 0)]
[DataRow(IntervalType.FromLastStart, 20)]
Expand All @@ -1424,7 +1486,7 @@
Action = () =>
{
runTimes.Enqueue(stopwatch.ElapsedMilliseconds);
Thread.Sleep(workMilliseconds);

Check warning on line 1489 in IntervalAction.Test/IntervalActionTests.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Do not use 'Thread.Sleep()' in a test.

Check warning on line 1489 in IntervalAction.Test/IntervalActionTests.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Do not use 'Thread.Sleep()' in a test.
},
});

Expand Down Expand Up @@ -1457,7 +1519,7 @@
Action = () =>
{
runTimes.Enqueue(stopwatch.ElapsedMilliseconds);
Thread.Sleep(workMilliseconds);

Check warning on line 1522 in IntervalAction.Test/IntervalActionTests.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Do not use 'Thread.Sleep()' in a test.

Check warning on line 1522 in IntervalAction.Test/IntervalActionTests.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Do not use 'Thread.Sleep()' in a test.
},
});

Expand Down
30 changes: 28 additions & 2 deletions IntervalAction/IntervalAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,13 @@ public sealed class IntervalAction : IDisposable
private CancellationTokenSource? ActionCancellation { get; set; }

/// <summary>
/// Gets the interval at which the action should be executed.
/// Gets or sets the interval at which the action should be executed.
/// </summary>
private TimeSpan ActionInterval { get; init; }
/// <remarks>
/// Only read or set while holding <see cref="Lock"/>, because <see cref="ChangeInterval"/> can
/// replace it while the polling loop is running.
/// </remarks>
private TimeSpan ActionInterval { get; set; }

/// <summary>
/// Gets the type of interval measurement for the action, either from the last completion or start time of the action.
Expand Down Expand Up @@ -285,6 +289,28 @@ public static IntervalAction Start(IntervalActionOptions intervalActionOptions)
return intervalAction;
}

/// <summary>
/// Changes how long the action waits between runs, without stopping it.
/// </summary>
/// <param name="actionInterval">
/// The new interval, measured as <see cref="IntervalActionOptions.ActionInterval"/> is. A negative
/// interval keeps the action from running, as it does when given to <see cref="Start"/>.
/// </param>
/// <remarks>
/// The new interval applies from the next poll, and is measured from the last run, which is kept:
/// a run that is already overdue under the new interval starts on the next poll, and one that is
/// not waits out the rest of it. A run in progress is not interrupted. The interval also survives
/// <see cref="Stop"/> and <see cref="Restart"/>, and changing it on a stopped or disposed instance
/// is allowed but runs nothing.
/// </remarks>
public void ChangeInterval(TimeSpan actionInterval)
{
lock (Lock)
{
ActionInterval = actionInterval;
}
}

/// <summary>
/// Stops the polling of the action.
/// </summary>
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,8 @@ var intervalAction = IntervalAction.Start(options);
// Later, adjust the interval
await Task.Delay(20000); // After 20 seconds

intervalAction.Stop();
options.ActionInterval = TimeSpan.FromSeconds(1);
intervalAction.Restart();
// Takes effect from the next poll, measured from the last run. The action keeps running.
intervalAction.ChangeInterval(TimeSpan.FromSeconds(1));

Console.WriteLine("Interval changed to 1 second");
```
Expand All @@ -164,6 +163,7 @@ It implements `IDisposable`.
| `StopAsync` | | `Task` | Stops the scheduled action, then completes once the polling loop has exited and any run in progress has finished. Use it before disposing anything the action uses. Called from inside the action, it does not wait for the run it is called from, so the action can stop its own polling |
| `Restart` | | `void` | Restarts a previously stopped action |
| `RestartAsync` | | `Task` | Restarts a previously stopped action, completing once the new polling loop has started |
| `ChangeInterval` | `TimeSpan actionInterval` | `void` | Changes the interval of a running action. It applies from the next poll and is measured from the last run, and a run in progress is not interrupted |
| `RethrowExceptions` | | `void` | Rethrows the exception the action last failed with, if any |
| `Dispose` | | `void` | Stops the action for good, like `Stop`, after which `Restart` throws `ObjectDisposedException`. An instance that is never stopped or disposed keeps running even when nothing references it |

Expand Down
Loading