• Felix Lange's avatar
    common/mclock: add Alarm (#26333) · 9e6a1c38
    Felix Lange authored
    Alarm is a timer utility that simplifies code where a timer needs to be rescheduled over
    and over. Doing this can be tricky with time.Timer or time.AfterFunc because the channel
    requires draining in some cases.
    
    Alarm is optimized for use cases where items are tracked in a heap according to their expiry
    time, and a goroutine with a for/select loop wants to be woken up whenever the next item expires.
    In this application, the timer needs to be rescheduled when an item is added or removed
    from the heap. Using a timer naively, these updates will always require synchronization
    with the global runtime timer datastructure to update the timer using Reset. Alarm avoids
    this by tracking the next expiry time and only modifies the timer if it would need to fire earlier
    than already scheduled.
    
    As an example use, I have converted p2p.dialScheduler to use Alarm instead of AfterFunc.
    9e6a1c38