Acme-Parataxis

 view release on metacpan or  search on metacpan

lib/Acme/Parataxis/Ticker.pod  view on Meta::CPAN

=pod

=encoding utf8

=head1 NAME

Acme::Parataxis::Ticker - Drift-Free Interval Timers for Scheduled Fibers

=head1 SYNOPSIS

    use v5.40;
    use Acme::Parataxis qw[async await_sleep];
    use Acme::Parataxis::Ticker;

    async {
        my $ticker = Acme::Parataxis::Ticker->new( interval => 1000 );    # 1 second ticks

        for ( 1 .. 5 ) {
            last unless my $tick_at = $ticker->wait_next;
            say "Tick at $tick_at; processing work...";
            await_sleep(250);    # work takes time, but ticker intervals do not drift!
        }

        $ticker->stop;           # stop the background ticker fiber
    };

=head1 DESCRIPTION

A standard loop of the form C<while (1) { do_work(); await_sleep($ms) }> suffers from cumulative timing drift: each
iteration takes C<$ms> I<plus> however long C<do_work()> took to execute. Over time, the schedule slides later and
later.

An C<Acme::Parataxis::Ticker> calculates intervals against absolute scheduled tick boundaries, sleeping only the
I<remainder> of each period. Ticks land on the boundary regardless of how long the consumer took to process the
preceding tick.

Under the hood, a private background fiber measures boundaries, sleeps the remainder of the interval, and pushes the
timestamp into a capacity-1 L<Acme::Parataxis::Channel>. Before publishing a new tick, any unread tick in the channel
is dropped. Exactly one tick is ever outstanding: a slow consumer silently drops missed intervals rather than
accumulating a stale backlog.

Calling C<stop()> terminates the ticker: any fiber parked in C<wait_next()> is unblocked and receives C<undef>, and the
background ticker fiber's sleep is interrupted so its background job is recalled immediately.

=head1 METHODS

=head2 C<new( interval =E<gt> $ms )>

    my $ticker = Acme::Parataxis::Ticker->new( interval => 500 );

Constructs a new ticker firing every C<$ms> milliseconds. The first tick lands one full interval after construction.
C<$ms> must be positive and defined.

Starts the internal background fiber immediately. Call C<stop()> when the ticker is no longer needed.

=head2 C<wait_next( )>

    while ( my $tick = $ticker->wait_next ) {
        execute_task();
    }

Parks the calling fiber until the next tick boundary arrives and returns that tick's scheduled timestamp. Returns
C<undef> once the ticker has been stopped. Must be called from within a scheduled fiber (croaks otherwise).



( run in 0.981 second using v1.01-cache-2.11-cpan-234fa220139 )