go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/clock/timer.go (about)

     1  // Copyright 2015 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package clock
    16  
    17  import (
    18  	"time"
    19  )
    20  
    21  // Timer is a wrapper around the time.Timer structure.
    22  //
    23  // A Timer is instantiated from a Clock instance and started via its Reset()
    24  // method.
    25  type Timer interface {
    26  	// GetC returns the underlying timer's channel.
    27  	//
    28  	// If the Timer is interrupted via Stop, its channel will block indefinitely.
    29  	GetC() <-chan TimerResult
    30  
    31  	// Reset configures the timer to expire after a specified duration.
    32  	//
    33  	// If the timer is already running, its previous state will be cleared and
    34  	// this method will return true. The channel returned by GetC() will not
    35  	// change due to Reset.
    36  	Reset(d time.Duration) bool
    37  
    38  	// Stop clears any timer tasking, rendering it inactive.
    39  	//
    40  	// Stop may be called on an inactive timer, in which case nothing will happen
    41  	// If the timer is active, it will be stopped and this method will return
    42  	// true.
    43  	//
    44  	// If a timer is stopped, its GetC channel will block indefinitely to avoid
    45  	// erroneously unblocking goroutines that are waiting on it. This is
    46  	// consistent with time.Timer.
    47  	Stop() bool
    48  }
    49  
    50  // TimerResult is the result for a timer operation.
    51  //
    52  // Time will be set to the time when the result was generated. If the source of
    53  // the result was prematurely terminated due to Context cancellation, Err will
    54  // be non-nil, and will indicate the cancellation reason.
    55  type TimerResult struct {
    56  	time.Time
    57  
    58  	// Err, if not nil, indicates that After did not finish naturally and contains
    59  	// the reason why.
    60  	Err error
    61  }
    62  
    63  // Incomplete will return true if the timer result indicates that the timer
    64  // operation was canceled prematurely due to Context cancellation or deadline
    65  // expiration.
    66  func (tr TimerResult) Incomplete() bool {
    67  	return tr.Err != nil
    68  }