Skip to content

singchia/go-timer

Folders and files

NameName
Last commit message
Last commit date
Jun 9, 2023
Jun 14, 2023
Jun 10, 2023
Jun 19, 2023
Jun 6, 2023
May 17, 2023
Jun 9, 2023
Jul 6, 2023
Jun 5, 2023
Jun 5, 2023
Jun 19, 2023
Nov 8, 2023
Jun 19, 2023
Jun 10, 2023
Jun 25, 2023
Jun 17, 2023
Jun 19, 2023

Repository files navigation

GO-TIMER

Go License Go Report Card

Overview

A high performance timer with minimal goroutines.

How it works

Features

  • One goroutine runs all
  • Goroutine safe
  • Clean and simple, no third-party deps at all
  • High performance with timing-wheels algorithm
  • Minimal resources use
  • Managed data and handler
  • Customizing channel
  • Well tested

Usage

Quick Start

package main

import (
	"log"
	"time"

	timer "github.com/singchia/go-timer/v2"
)

func main() {
	t1 := time.Now()
	// new timer
	t := timer.NewTimer()
	// add a tick in 1s
	tick := t.Add(time.Second)
	// wait for it
	<-tick.C()
	// tick fired as time is up, calculate and print the elapse
	log.Printf("time elapsed: %fs\n", time.Now().Sub(t1).Seconds())
}

Async handler

package main

import (
	"log"
	"sync"
	"time"

	timer "github.com/singchia/go-timer/v2"
)

func main() {
	// we need a wait group since using async handler
	wg := sync.WaitGroup{}
	wg.Add(1)
	// new timer
	t := timer.NewTimer()
	// add a tick in 1s with current time and a async handler
	t.Add(time.Second, timer.WithData(time.Now()), timer.WithHandler(func(event *timer.Event) {
		defer wg.Done()
		// tick fired as time is up, calculate and print the elapse
		log.Printf("time elapsed: %fs\n", time.Now().Sub(event.Data.(time.Time)).Seconds())
	}))

	wg.Wait()
}

With cyclically

package main

import (
	"log"
	"time"

	timer "github.com/singchia/go-timer/v2"
)

func main() {
	t1 := time.Now()
	// new timer
	t := timer.NewTimer()
	// add cyclical tick in 1s
	tick := t.Add(time.Second, timer.WithCyclically())
	for {
		// wait for it cyclically
		<-tick.C()
		t2 := time.Now()
		// calculate and print the elapse
		log.Printf("time elapsed: %fs\n", t2.Sub(t1).Seconds())
		t1 = t2
	}
}

License

© Austin Zhai, 2015-2025

Released under the Apache License 2.0