golang 定时器

时间:2025-05-14 11:57:00

 写法一:

package main

import (
	"fmt"
	"sync"
	"time"
)

type DemoTicker struct {
	ch   <-chan time.Time
	stop chan struct{}
	sg   *sync.WaitGroup
}

func main() {
	count, stopCount := 0, 5
	demo := DemoTicker{
		ch:   time.Tick(time.Second * 1),
		stop: make(chan struct{}),
		sg:   &sync.WaitGroup{},
	}
	demo.sg.Add(1)
	go func() {
		demo.sg.Done()
		for {
			select {
			case <-demo.ch:
				println("tick1")
				count++
				if count == stopCount {
					demo.stop <- struct{}{}
				}
			}
		}
	}()
	<-demo.stop
	demo.sg.Wait()
	fmt.Println("done")

}

结果:
tick1
tick1
tick1
tick1
tick1
done

写法二:

package main

import (
	"fmt"
	"sync"
	"time"
)

type DemoTicker struct {
	*time.Ticker
	stop chan struct{}
	sg   *sync.WaitGroup
}

func main() {
	count, stopCount := 0, 5
	demo := DemoTicker{
		Ticker: time.NewTicker(time.Second * 1),
		stop:   make(chan struct{}),
		sg:     &sync.WaitGroup{},
	}
	demo.sg.Add(1)
	ticker := demo.Ticker
	go func() {
		defer demo.sg.Done()
		for {
			select {
			case <-ticker.C:
				fmt.Printf("count:%d\n", count)
				count++
				if count == stopCount {
					demo.stop <- struct{}{}
					ticker.Stop()
				}
			}
		}
	}()
	<-demo.stop
	fmt.Printf("stop")

}


结果

API server listening at: 127.0.0.1:59859
WARNING: undefined behavior - Go version go1.18.10 is too old for this version of Delve (minimum supported version 1.21)
count:0
count:1
count:2
count:3
count:4
stop
调试器 已完成,退出代码为 0