-
Notifications
You must be signed in to change notification settings - Fork 1
Timer Manager
Centralized gameplay timer service with named timers supporting one-shot and looping modes, pause/resume, rate control, and fire count tracking.
Source: SparkEngine/Source/Utils/TimerManager.h
The Timer Manager provides a structured alternative to ad-hoc cooldown tracking in gameplay code. Inspired by Unreal Engine's FTimerManager, it maintains a pool of named timers that tick each frame. Timers fire a callback when their interval elapses, and can be configured as one-shot (auto-removed after firing) or looping (repeats until explicitly cleared).
Each timer has a human-readable name used for lookup, which makes debugging straightforward. Timers can be paused and resumed without losing elapsed progress, and their rate (interval) can be changed at runtime. The system tracks how many times each timer has fired, useful for gameplay mechanics like damage-over-time stacks or periodic spawning.
The update loop processes pending removals first (to safely handle timers cleared during callbacks), then advances all active timers. Looping timers subtract the rate from elapsed time rather than resetting to zero, which correctly handles cases where deltaTime exceeds the timer interval. One-shot timers are automatically queued for removal after firing.
| Class / Struct | Description |
|---|---|
TimerManager |
Singleton that owns and ticks all named timers |
ManagedTimer |
A single timer: name, rate, elapsed, looping flag, state, callback, fire count |
TimerState |
Enum: Active (counting down), Paused (frozen), Expired (pending removal) |
TimerCallback |
std::function<void()> called when the timer fires |
auto& timers = Spark::TimerManager::GetInstance();
timers.Initialize();
// One-shot timer: respawn player after 3 seconds
timers.SetTimer("respawn", 3.0f, false, []() {
SpawnPlayer();
});
// Looping timer: regenerate health every 1 second
timers.SetTimer("regen", 1.0f, true, [&player]() {
player.health = std::min(player.health + 5, player.maxHealth);
});
// Looping timer: spawn enemies every 10 seconds
timers.SetTimer("enemy_wave", 10.0f, true, []() {
SpawnEnemyWave();
});
// Pause regen during combat
timers.PauseTimer("regen");
// Resume when combat ends
timers.ResumeTimer("regen");
// Speed up enemy spawns mid-game
timers.SetTimerRate("enemy_wave", 5.0f);
// Query timer state
float remaining = timers.GetRemainingTime("respawn");
bool active = timers.IsTimerActive("respawn");
uint32_t waves = timers.GetFireCount("enemy_wave");
// Cancel a timer
timers.ClearTimer("regen");
// In the main loop
void MainLoop(float deltaTime)
{
timers.Update(deltaTime);
// ...
}| Method | Return | Description |
|---|---|---|
Initialize() |
void |
Initialize the timer manager and clear all timers |
Shutdown() |
void |
Clear all timers and shut down |
Update(deltaTime) |
void |
Tick all active timers; call once per frame |
| Method | Return | Description |
|---|---|---|
SetTimer(name, rate, looping, callback) |
void |
Create or replace a named timer |
ClearTimer(name) |
void |
Remove a timer (deferred to next Update) |
ClearAllTimers() |
void |
Remove all timers immediately |
PauseTimer(name) |
void |
Pause a timer, preserving elapsed time |
ResumeTimer(name) |
void |
Resume a paused timer |
SetTimerRate(name, newRate) |
void |
Change the interval of an existing timer |
ResetTimer(name) |
void |
Reset elapsed time to zero and set state to Active |
| Method | Return | Description |
|---|---|---|
IsTimerActive(name) |
bool |
Whether the timer exists and is actively counting |
TimerExists(name) |
bool |
Whether the timer exists in any state |
IsTimerPaused(name) |
bool |
Whether the timer is paused |
GetRemainingTime(name) |
float |
Seconds until next fire |
GetElapsedTime(name) |
float |
Seconds since last fire (or since creation) |
GetFireCount(name) |
uint32_t |
Number of times this timer has fired |
GetTimerCount() |
size_t |
Total number of managed timers |
GetTimerNames() |
vector<string> |
Names of all timers |
- Tween System -- value interpolation over time (complementary to timers)
- Coroutine Scheduler -- async frame-based scheduling
- ECS Systems -- gameplay systems can use TimerManager for periodic logic
- Event System -- timers can fire events instead of direct callbacks
Published from 936a8401bf15. Edit the canonical source in wiki/.
- Documentation
- Docs route
- Wiki index
- Guides
- Tutorials
- Samples
- Examples
- API Reference
- API route
- Reference
- Build Guide
- Dependencies
- FAQ
- Changelog
- Roadmap
- Contributing
- Code of Conduct
- Home
- FAQ
- Getting Started
- Quick-Start Tutorial
- Making Your First Game
- Making Your First Multiplayer Game
- Artist Workflow Guide
- Editor Walkthrough
- Migration Guide
- How SparkEngine Works
- Architecture Overview
- Engine Architecture Flowchart
- Creating a Game Module
- Game Modules (catalog)
- Entity Component System
- Rendering and Graphics
- Physics
- Cloth Simulation
- Audio
- Input System
- Camera System
- Scripting with AngelScript
- Visual Scripting
- AI and Navigation
- Animation
- 2D Systems
- Networking
- Dedicated Server
- Multiplayer Quick Start
- Area Server Architecture
- Scene Management
- Large World Support
- Collaborative Editing
- Coroutine System
- Event System
- Event Response System
- Job System
- UI System
- UI Layout Extensions
- Localization
- Dialogue System
- Destruction System
- Replay System
- Achievement System
- Loading System
- Mod System
- Content Delivery
- Tween System
- Memory Integrity
- Gameplay Systems
- Terrain and Procedural Generation
- Save System
- Persistence System
- Day Night Cycle and Weather
- Cinematic Sequencer
- Runtime Prefabs
- SparkEditor
- Editor Tutorials
- SparkConsole
- SparkDaemon
- Shader Pipeline
- Asset Pipeline
- Asset Validation
- Asset Migration
- Game Packaging
- Online Services
- DataTable System
- Loot and Crafting System
- CSG System
- Font System
- Timer Manager
- Movie Render Pipeline
- HLOD and World Partition
- Remote Debug System
- Selection Manager
- Asset Dependency Graph
- Editor Automation
- File Watcher
- Project Templates
- System Requirements
- VR Support
- Mobile Platform
- Accessibility
- Platform Input
- Cross-Compilation: Wine Testing
- RHI Abstraction Layer
- D3D11 Backend
- D3D12 Backend
- Vulkan Backend
- OpenGL Backend
- Metal Backend
- DXR Raytracing
- Hybrid Ray Tracing
- Upscaling (DLSS/FSR)
- Render Graph
- Shader Graph
- GPU Particles
- GPU-Driven Rendering
- Volumetric Fog
- Volumetric Clouds
- Global Illumination
- Virtual Texturing
- Water Rendering
- Clustered Lighting
- Material System
- Post-Processing
- Shadow System
- Particle System
- Decal System
- Sky and Atmosphere
- Foliage System
- Mesh Shaders
- Neural Rendering
- Configuration Reference
- Performance Tips
- Benchmark Framework
- Threading Model
- Memory Safety
- Memory Management Patterns
- Build System and CMake Modules
- Profiler and Debugging
- Performance Profiling Guide
- Telemetry System
- Golden Image Testing
- Utilities
- Testing
- Codebase Statistics
- Codebase Health
- Error Handling Patterns
- Hot Reload Overview
- Troubleshooting
- Contributing
- Workflow Patterns
- Build Optimizations
- CI Reproducible Builds
- GitHub API and PR Checks
- Git Rebase Conflicts
- Clang-Format
- Code Quality Violations
- AI Bloat Pattern
- MinGW + Wine Cross-Compilation
- Live Editor Testing
- Engine & Renderer Landscape
- DuetOS Portability Catalog
- Five-Engine Analysis
- Eleven-Engine Analysis
- ThorVG / Unity Graphics Analysis
- Advanced Techniques Catalog
- Third-Party Library Evaluation
- Engine Viability Evaluation
- Engine Feature Recommendations
- Project Recommendations
- Mac Compatibility Analysis
- Codebase Observations
- Codebase Bloat Audit
- Test Suite Audit
- Documentation Coverage Audit
- ThirdParty Dependencies Audit
- Load Test Baseline
- Gameplay Systems Status
- SparkGame Module Status
- Stub and Abandoned Features
- Memory Integrity System
- Memory Safety Evaluation
- Hardware Acceleration Systems
- Jolt Physics Integration
- GPU/CPU Separation Plan
- Daemon Services Architecture
- Reflection & Polymorphism Refactoring Plan
- SparkBuild In-Tree
- Wine No-JobSystem Breakthrough
- Wine Role and Fallback Tiers