A .NET library that provides a simple way to execute an action at a specified interval.
IntervalAction is a .NET library that provides a simple and flexible way to execute an action at a specified interval. It offers precise control over execution timing, various interval types, and easy management of scheduled actions. Designed for scenarios where you need recurring tasks like polling, background processing, or timed updates.
- Flexible Timing: Execute actions at precise intervals
- Interval Types: Choose between running intervals from last start or last completion
- Configurable Polling: Fine-tune polling frequency for better performance
- Immediate Execution: Option to execute actions immediately on start
- Start/Stop Control: Easily pause and restart scheduled actions
- Thread Safety: Safe for concurrent access from multiple threads
- Low Overhead: Minimal resource usage during idle periods
- Supports .NET 8.0 and .NET 9.0: Modern .NET support
Install-Package ktsu.IntervalActiondotnet add package ktsu.IntervalAction<PackageReference Include="ktsu.IntervalAction" Version="x.y.z" />using ktsu.IntervalAction;
var intervalAction = IntervalAction.Start(new()
{
Action = () => Console.WriteLine("Hello, World!"),
ActionInterval = TimeSpan.FromSeconds(1),
PollingInterval = TimeSpan.FromMilliseconds(100), // Optional, default is 1 second
IntervalType = IntervalType.FromLastStart // Optional, default is FromLastCompletion
});
// An action will execute immediately and then every second
// outputting "Hello, World!" to the console until stopped
intervalAction.Stop();
// The action will no longer execute until you call Restart()
intervalAction.Restart();using ktsu.IntervalAction;
var intervalAction = IntervalAction.Start(new()
{
Action = () =>
{
Console.WriteLine($"Action started at: {DateTimeOffset.Now}");
// Simulate a task that takes some time to complete
Task.Delay(500).Wait();
Console.WriteLine($"Action completed at: {DateTimeOffset.Now}");
},
ActionInterval = TimeSpan.FromSeconds(2),
PollingInterval = TimeSpan.FromMilliseconds(100),
IntervalType = IntervalType.FromLastCompletion // Waits until the action completes before starting the interval timer
});
// The action will execute immediately and then every 2 seconds after the previous execution completesusing ktsu.IntervalAction;
var intervalAction = IntervalAction.Start(new()
{
// AsyncAction, not Action: an async lambda assigned to Action becomes async void, which
// returns at its first await, so runs would overlap and exceptions would crash the process
AsyncAction = async cancellationToken =>
{
Console.WriteLine("Starting long-running task...");
// Simulate a long-running task; the token is cancelled by Stop()
await Task.Delay(5000, cancellationToken);
Console.WriteLine("Long-running task completed");
},
ActionInterval = TimeSpan.FromSeconds(10),
IntervalType = IntervalType.FromLastCompletion // Important for long-running tasks
});
// For cleanup when done
await Task.Delay(60000); // Run for 1 minute
// StopAsync cancels the token, then waits for the run in progress to finish, so nothing the
// action uses is disposed while it is still running. Stop() returns without waiting.
await intervalAction.StopAsync();
intervalAction.RethrowExceptions(); // Reports a failure from the final run, if there was oneusing ktsu.IntervalAction;
// Create with initial settings
var options = new IntervalActionOptions
{
Action = () => Console.WriteLine($"Tick at {DateTime.Now}"),
ActionInterval = TimeSpan.FromSeconds(5)
};
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();
Console.WriteLine("Interval changed to 1 second");The main class for scheduling recurring actions.
| Name | Type | Description |
|---|---|---|
IsRunning |
bool |
Indicates if the action is currently scheduled to run |
Options |
IntervalActionOptions |
The current options for this interval action |
| Name | Parameters | Return Type | Description |
|---|---|---|---|
Start |
IntervalActionOptions options |
IntervalAction |
Static factory method to create and start an interval action |
Stop |
void |
Stops the scheduled action from running; a run already in progress is not waited for | |
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 | |
Restart |
void |
Restarts a previously stopped action |
Configuration options for an interval action.
| Name | Type | Description |
|---|---|---|
Action |
Action |
The action to execute at intervals (set this or AsyncAction) |
AsyncAction |
Func<CancellationToken, Task> |
An asynchronous action to execute at intervals; a run lasts until its task completes, and the token is cancelled by Stop() (set this or Action) |
ActionInterval |
TimeSpan |
The interval between executions (required) |
PollingInterval |
TimeSpan |
How frequently to check if action should run (optional, default 1 second; must be between 1 ms and int.MaxValue ms, about 24.8 days) |
IntervalType |
IntervalType |
Determines how intervals are measured (optional, default FromLastCompletion) |
Defines how the interval is measured.
| Value | Description |
|---|---|
FromLastCompletion |
The interval starts after the action has completed |
FromLastStart |
The interval starts when the action begins executing |
Contributions are welcome! Here's how you can help:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Please make sure to update tests as appropriate and adhere to the existing coding style.
This project is licensed under the MIT License - see the LICENSE.md file for details.
Check the CHANGELOG.md for detailed release notes and version changes.
Special thanks to all contributors and the .NET community for their support.