multitimer

package module
v0.0.0-...-4fc76de Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 2, 2023 License: Apache-2.0 Imports: 3 Imported by: 0

README

multitimer

The package provides a convenient way of managing several timers.

Badges

Build Status Go Report Card

Installation

To start using this package, run:

$ go get github.com/avdva/multitimer

Description

Timer sends payload to its chan after a delay. One can schedule several events, but only one real timer will be used. It is safe to use a Timer object concurrently. Timer may drop messages, if the reader does not read fast enough, so it's important to choose a correct channel capacity.

API

create:
// New returns a timer with capacity set to 1.
New[T any]() 
// NewWithCapacity returns a timer for given capacity.
NewWithCapacity[T any](cap int)

use:
// Schedule schedules a timer to fire after the delay.
// The payload will be sent to C.
Schedule(delay time.Duration, payload T)
// ScheduleAt schedules a timer to fire at the specific moment.
// The payload will be sent to C.
ScheduleAt(when time.Time, payload T)
// Stop cancels all the timers.
Stop() 

Examples

timer := NewWithCapacity[int](10)
for i := 0; i < 10; i++ {
	timer.Schedule(100*time.Millisecond*time.Duration(i+1), i)
}
for i := 0; i < 10; i++ {
	fmt.Println(<-timer.C)
}

Contact

Aleksandr Demakin

License

Source code is available under the Apache License Version 2.0.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Timer

type Timer[T any] struct {
	C chan T
	// contains filtered or unexported fields
}

Timer sends payload to its chan after a delay. One can schedule several events, but only one real timer will be used. It is safe to use a Timer object concurrently. Timer may drop messages, if the reader does not read fast enough, so it's important to choose a correct chan capacity.

func New

func New[T any]() *Timer[T]

New returns a timer with capacity set to 1.

func NewWithCapacity

func NewWithCapacity[T any](cap int) *Timer[T]

NewWithCapacity returns a timer for given capacity.

func (*Timer[T]) Schedule

func (mt *Timer[T]) Schedule(delay time.Duration, payload T)

Schedule schedules a timer to fire after the delay. The payload will be sent to C.

func (*Timer[T]) ScheduleAt

func (mt *Timer[T]) ScheduleAt(when time.Time, payload T)

ScheduleAt schedules a timer to fire at the specific moment. The payload will be sent to C.

func (*Timer[T]) Stop

func (mt *Timer[T]) Stop()

Stop cancels all timers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL