Golang实现Ticker应用的开发与实践
Golang实现Ticker应用的开发与实践 我准备了一个用于优雅关闭的计时器应用程序的要点。
我希望听到您的评论和改进建议。
package main
import (
"log"
"os"
"os/signal"
"time"
)
//ticker interval
1 回复
更多关于Golang实现Ticker应用的开发与实践的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
这是一个很好的优雅关闭Ticker实现。以下是针对代码的评论和优化示例:
package main
import (
"context"
"log"
"os"
"os/signal"
"sync"
"time"
)
type TickerService struct {
interval time.Duration
ticker *time.Ticker
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
}
func NewTickerService(interval time.Duration) *TickerService {
ctx, cancel := context.WithCancel(context.Background())
return &TickerService{
interval: interval,
ctx: ctx,
cancel: cancel,
}
}
func (ts *TickerService) Start() {
ts.wg.Add(1)
ts.ticker = time.NewTicker(ts.interval)
go func() {
defer ts.wg.Done()
defer ts.ticker.Stop()
for {
select {
case <-ts.ctx.Done():
log.Println("Ticker service stopping...")
return
case t := <-ts.ticker.C:
ts.handleTick(t)
}
}
}()
}
func (ts *TickerService) handleTick(t time.Time) {
log.Printf("Tick at %v", t.Format(time.RFC3339))
// 这里添加实际的业务逻辑
}
func (ts *TickerService) Stop() {
ts.cancel()
ts.wg.Wait()
log.Println("Ticker service stopped")
}
func main() {
// 创建带超时的context
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
// 初始化服务
tickerService := NewTickerService(2 * time.Second)
tickerService.Start()
// 等待中断信号
<-ctx.Done()
// 优雅关闭
tickerService.Stop()
log.Println("Application shutdown complete")
}
这个实现使用了context进行更精细的控制,添加了WaitGroup确保goroutine完全退出,并通过结构体封装提供了更好的可测试性。

