periodic

package
v1.75.4 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2023 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package periodic allow to execute a specified function periodically.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Periodic

type Periodic struct {
	// contains filtered or unexported fields
}

Periodic instance.

func New

func New(interval time.Duration, jitter time.Duration, timeout time.Duration, task TaskFn) (*Periodic, error)

New creates a new Periodic instance. The jitter parameter is the maximum random Jitter time between each function call. This is useful to avoid the Thundering herd problem (https://en.wikipedia.org/wiki/Thundering_herd_problem).

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/Vonage/gosrvlib/pkg/periodic"
)

func main() {
	count := make(chan int, 1)

	count <- 0

	// example task to execute periodically
	task := func(_ context.Context) {
		v := <-count
		count <- (v + 1)
	}

	interval := 20 * time.Millisecond
	jitter := 2 * time.Millisecond
	timeout := 2 * time.Millisecond

	// create a new periodic job
	p, err := periodic.New(interval, jitter, timeout, task)
	if err != nil {
		close(count)
		log.Fatal(err)
	}

	// start the periodic job
	p.Start(context.TODO())

	// wait for 3 times the interval
	wait := 3 * interval
	time.Sleep(wait)

	// stop the periodic job
	p.Stop()

	fmt.Println(<-count)

	close(count)

}
Output:

3

func (*Periodic) Start

func (p *Periodic) Start(ctx context.Context)

Start the periodic execution.

func (*Periodic) Stop

func (p *Periodic) Stop()

Stop the periodic execution. It may block until the last running function returns.

type TaskFn

type TaskFn func(context.Context)

TaskFn is the type of function to be periodically executed.

Jump to

Keyboard shortcuts

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