IntervalTimer
Coding Style wiki
IntervalTimer is a JavaScript-setInterval-style interval ticker (UniTask-driven) that fires an Action every specified milliseconds, supporting ignoreTimeScale (whether to ignore Time.timeScale) and SetIntervalOnThread (running on the thread pool). It can also be created and managed centrally through the static manager IntervalSetter.
| Namespace | OxGKit.TimeSystem |
| Type | public class IntervalTimer |
| Source | IntervalTimer.cs |
using OxGKit.TimeSystem;
Quick Start
using OxGKit.TimeSystem;
var intervalTimer = new IntervalTimer();
// Fire every 1000 milliseconds
intervalTimer.SetInterval(() =>
{
// Periodic work
}, 1000);
// Always stop when the feature exits
intervalTimer.StopInterval();
General Rules
- The first trigger fires after the first interval (wait first, then invoke), and it keeps cycling afterwards.
- While an instance is already running, calling
SetInterval/SetIntervalOnThreadagain has no effect — call StopInterval first, then set it again. ignoreTimeScaledefaults to false: the interval is measured in Unity scaled time (no triggering whileTime.timeScale = 0); set it to true to measure in unscaled time.
Important The interval ticking is a UniTask loop — when the owner (feature/scene) exits, always call StopInterval, otherwise the loop keeps running; if the callback throws inside the loop, the timer stops automatically and rethrows.
Constructors
public IntervalTimer()
Creates the interval ticker (call SetInterval afterwards to start it).
Methods
Method Overview
| Method | Description |
|---|---|
| SetInterval | Starts interval ticking (fires an Action every specified milliseconds). |
| SetIntervalOnThread | Starts interval ticking switched to the thread pool. |
| StopInterval | Stops interval ticking. |
| IsRunning | Whether the ticker is running. |
SetInterval
public void SetInterval(Action action, int milliseconds, bool ignoreTimeScale = false)
Starts interval ticking, invoking action every milliseconds milliseconds; calling it again while already running has no effect.
// Fire every 500 milliseconds, ignoring Time.timeScale
intervalTimer.SetInterval(() => { /* ... */ }, 500, true);
SetIntervalOnThread
public void SetIntervalOnThread(Action action, int milliseconds, bool ignoreTimeScale = false)
Starts interval ticking switched to the thread pool first (UniTask.SwitchToThreadPool); calling it again while already running has no effect.
Important The callback may run off the Unity main thread — do not access UnityEngine objects directly (marshal back to the main thread yourself).
Attention WebGL does not support multithreading — no switch happens on WebGL (behaves the same as SetInterval).
StopInterval
public void StopInterval()
Stops interval ticking and cancels the internal CancellationTokenSource; after stopping, SetInterval can be called again to restart.
IsRunning
public bool IsRunning()
Returns whether the interval ticker is currently running.