ticker

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2024 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Overview

Package ticker provides iterators for timed loops using Go's iter package.

It offers two main functions: After and Before, which allow you to create timed loops with different behaviors.

Features

  • After: Creates an iterator that executes the loop body after waiting for a specified duration.
  • Before: Creates an iterator that executes the loop body before waiting for a specified duration.
  • Both functions support context cancellation for immediate loop termination.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func After

func After(ctx context.Context, d time.Duration) iter.Seq2[int, time.Time]

After returns an iterator that passes control to the loop body after waiting for duration d.

This iterator waits first and then executes the loop body.

The iterator passes the loop index and the current time returned by internal time.Ticker to the loop body.

The loop and wait can be interrupted immediately by canceling the context.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/goaux/iter/ticker"
)

func main() {
	unit := 100 * time.Millisecond
	start := time.Now()
	for i, now := range ticker.After(context.TODO(), 3*unit) {
		elapse := now.Sub(start)
		fmt.Println(i, ((elapse / unit) * unit).String())
		if elapse >= 9*unit {
			break
		}
	}
}
Output:

0 300ms
1 600ms
2 900ms

func Before

func Before(ctx context.Context, d time.Duration) iter.Seq2[int, time.Time]

Before returns an iterator that passes control to the loop body before waiting for duration d.

This iterator executes the loop body first and then waits.

The iterator passes the loop index and the current time returned by internal time.Ticker to the loop body.

The loop and wait can be interrupted immediately by canceling the context.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/goaux/iter/ticker"
)

func main() {
	unit := 100 * time.Millisecond
	start := time.Now()
	for i, now := range ticker.Before(context.TODO(), 3*unit) {
		elapse := now.Sub(start)
		fmt.Println(i, ((elapse / unit) * unit).String())
		if elapse >= 9*unit {
			break
		}
	}
}
Output:

0 0s
1 300ms
2 600ms
3 900ms

Types

This section is empty.

Jump to

Keyboard shortcuts

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