diff --git a/CLAUDE.md b/CLAUDE.md
index 3cb652a..1a0eecb 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -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
diff --git a/IntervalAction.Test/IntervalActionTests.cs b/IntervalAction.Test/IntervalActionTests.cs
index 5fbe912..f3e4c30 100644
--- a/IntervalAction.Test/IntervalActionTests.cs
+++ b/IntervalAction.Test/IntervalActionTests.cs
@@ -1401,6 +1401,68 @@ public void ARunIsDueOnceTheActionIntervalHasPassed()
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);
+ }
+
+ intervalAction.ChangeInterval(TimeSpan.FromMilliseconds(20));
+
+ while (Volatile.Read(ref counter) < 3 && stopwatch.Elapsed < TimeSpan.FromSeconds(10))
+ {
+ await Task.Delay(10).ConfigureAwait(false);
+ }
+
+ 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)]
diff --git a/IntervalAction/IntervalAction.cs b/IntervalAction/IntervalAction.cs
index 389377f..9ab6386 100644
--- a/IntervalAction/IntervalAction.cs
+++ b/IntervalAction/IntervalAction.cs
@@ -113,9 +113,13 @@ public sealed class IntervalAction : IDisposable
private CancellationTokenSource? ActionCancellation { get; set; }
///
- /// Gets the interval at which the action should be executed.
+ /// Gets or sets the interval at which the action should be executed.
///
- private TimeSpan ActionInterval { get; init; }
+ ///
+ /// Only read or set while holding , because can
+ /// replace it while the polling loop is running.
+ ///
+ private TimeSpan ActionInterval { get; set; }
///
/// Gets the type of interval measurement for the action, either from the last completion or start time of the action.
@@ -285,6 +289,28 @@ public static IntervalAction Start(IntervalActionOptions intervalActionOptions)
return intervalAction;
}
+ ///
+ /// Changes how long the action waits between runs, without stopping it.
+ ///
+ ///
+ /// The new interval, measured as is. A negative
+ /// interval keeps the action from running, as it does when given to .
+ ///
+ ///
+ /// 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
+ /// and , and changing it on a stopped or disposed instance
+ /// is allowed but runs nothing.
+ ///
+ public void ChangeInterval(TimeSpan actionInterval)
+ {
+ lock (Lock)
+ {
+ ActionInterval = actionInterval;
+ }
+ }
+
///
/// Stops the polling of the action.
///
diff --git a/README.md b/README.md
index a0e68c2..172bf89 100644
--- a/README.md
+++ b/README.md
@@ -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");
```
@@ -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 |