class Termisu::Event::Source::Timer

Overview

Periodic timer event source.

Generates Event::Tick events at a configurable interval for animations, game loops, and other time-based operations.

Usage

timer = Termisu::Event::Source::Timer.new(interval: 16.milliseconds)
loop = Termisu::Event::Loop.new
loop.add_source(timer)
loop.start

while event = loop.output.receive?
  case event
  when Termisu::Event::Tick
    position += velocity * event.delta.total_seconds
    puts "Frame #{event.frame}, elapsed: #{event.elapsed}"
  end
end

Timing Behavior

Thread Safety

Uses Atomic(Bool) for the running state. Safe to call #start/#stop from different fibers. The #interval= setter is thread-safe.

Defined in:

termisu/event/source/timer.cr

Constant Summary

DEFAULT_INTERVAL = 16.milliseconds

Default tick interval (~60 FPS).

Log = Termisu::Logs::Event

Constructors

Instance Method Summary

Instance methods inherited from class Termisu::Event::Source

name : String name, running? : Bool running?, start(output : Channel(Event::Any)) : Nil start, stop : Nil stop

Constructor Detail

def self.new(interval : Time::Span = DEFAULT_INTERVAL) #

Creates a new timer with the specified interval.

  • #interval - Time between tick events (default: 16ms for ~60 FPS)

[View source]

Instance Method Detail

def interval : Time::Span #

Returns the current interval between ticks.


[View source]
def interval=(value : Time::Span) #

Sets the interval between ticks.

The new interval takes effect on the next tick. Can be changed while the timer is running.


[View source]
def name : String #

Returns the source name for identification.


[View source]
def running? : Bool #

Returns true if the timer is currently running.


[View source]
def start(output : Channel(Event::Any)) : Nil #

Starts generating tick events to the output channel.

Spawns a fiber that sleeps for the interval and sends Event::Tick events. The fiber continues until #stop is called.

Prevents double-start with compare_and_set.


[View source]
def stop : Nil #

Stops generating tick events.

Sets the running flag to false, causing the fiber to exit on its next iteration. Uses compare_and_set for idempotent stop operations - calling stop twice is safe.


[View source]