ctxticker

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2023 License: MIT Imports: 2 Imported by: 0

README

Description

This is simple wrapper on time.Ticker that takes into consideration context.Context state

Examples

1. Service example

package main

import (
	"context"
	"fmt"
	"github.com/go-auxiliaries/ctxticker"
	"time"
	"sync"
)

type Service struct {
	ticker *ctxticker.Ticker
	period time.Duration
	body func(ctx context.Context)
}

// Service that is running body every period
func NewService(period time.Duration, body func(ctx context.Context)) *Service {
    return &Service{
		period: period,
		body: body,
    }
}

func (s *Service) Start(ctx context.Context) {
	s.ticker = ctxticker.New(ctx, time.Duration(0), time.Second, true)
	go s.serviceBodyCycle(ctx)
}

func (s *Service) Stop() {
	if s.ticker != nil {
		s.ticker.Stop()
    }
}

func (s *Service) serviceBodyCycle(ctx context.Context) {
	defer s.ticker.Stop()
    for {
        if err := s.ticker.Tick(); err != nil {
            break
        }
        s.body(ctx)
    }
}

2. Service example, body execution time is limited

package main

import (
	"context"
	"fmt"
	"github.com/go-auxiliaries/ctxticker"
	"time"
	"sync"
)

type Service struct {
	ticker *ctxticker.Ticker
	period time.Duration
	body func(ctx context.Context)
}

// Service that is running body every period, 
// but body execution time is limited by context timeout
func NewService(period time.Duration, body func(ctx context.Context)) *Service {
	return &Service{
		period: period,
		body: body,
	}
}

func (s *Service) Start(ctx context.Context) {
	s.ticker = ctxticker.New(ctx, time.Duration(0), time.Second, true)
	go s.serviceBodyCycle(ctx)
}

func (s *Service) Stop() {
	if s.ticker != nil {
		s.ticker.Stop()
	}
}

func (s *Service) serviceBodyCycle(ctx context.Context) {
	defer s.ticker.Stop()
	for {
		if err := s.ticker.Tick(); err != nil {
			break
		}
		s.body(ctx)
	}
}

func (s *Service) serviceBody(ticker *ctxticker.Ticker) {
	ctx, cancel := ticker.GetTickContext()
    defer cancel()
	s.body(ctx)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Ticker

type Ticker struct {
	Cancel  func()
	Ctx     context.Context
	Timeout time.Duration
	Period  time.Duration
	// contains filtered or unexported fields
}

func New

func New(ctx context.Context, timeout, period time.Duration, firstTickFast bool) *Ticker

func (*Ticker) GetTickContext

func (ct *Ticker) GetTickContext() (context.Context, context.CancelFunc)

func (*Ticker) Release

func (ct *Ticker) Release()

func (*Ticker) Stop

func (ct *Ticker) Stop()

func (*Ticker) Tick

func (ct *Ticker) Tick() error

func (*Ticker) Trigger

func (ct *Ticker) Trigger()

Jump to

Keyboard shortcuts

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