From 8c45a075b20c7a3178e9b6ed720084f74c95ddbc Mon Sep 17 00:00:00 2001 From: searKing <471030698@qq.com> Date: Tue, 3 Sep 2024 19:58:51 +0800 Subject: [PATCH] feat(time): Use [time.Timer] instead since go1.23. Timer.Stop documentation example no longer leads to deadlocks, as Timer/Ticker channels not receivable with old values after Stop or Reset returns. https://github.com/golang/go/issues/27169 https://github.com/golang/go/issues/37196 https://github.com/golang/go/issues/14383 --- go/time/{sleep.go => sleep_go1.22.go} | 2 ++ go/time/sleep_go1.23.go | 42 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) rename go/time/{sleep.go => sleep_go1.22.go} (99%) create mode 100644 go/time/sleep_go1.23.go diff --git a/go/time/sleep.go b/go/time/sleep_go1.22.go similarity index 99% rename from go/time/sleep.go rename to go/time/sleep_go1.22.go index aa128eb3..5d7b399f 100644 --- a/go/time/sleep.go +++ b/go/time/sleep_go1.22.go @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !go1.23 + package time import ( diff --git a/go/time/sleep_go1.23.go b/go/time/sleep_go1.23.go new file mode 100644 index 00000000..a2d34b98 --- /dev/null +++ b/go/time/sleep_go1.23.go @@ -0,0 +1,42 @@ +// Copyright 2020 The searKing Author. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.23 + +package time + +import ( + "time" +) + +// Timer to fix time: Timer.Stop documentation example easily leads to deadlocks +// https://github.com/golang/go/issues/27169 +// +// Deprecated: Use [time.Timer] instead since go1.23. +// https://github.com/golang/go/issues/37196 +// https://github.com/golang/go/issues/14383 +type Timer = time.Timer + +// Deprecated: Use [time.NewTimer] instead since go1.23. +func NewTimer(d time.Duration) *Timer { + return time.NewTimer(d) +} + +// Deprecated: Use [time.Timer] instead since go1.23. +func WrapTimer(t *time.Timer) *Timer { + return t +} + +// Deprecated: Use [time.After] instead since go1.23. +func After(d time.Duration) <-chan time.Time { + return NewTimer(d).C +} + +// Deprecated: Use [time.AfterFunc] instead since go1.23. +func AfterFunc(d time.Duration, f func()) *Timer { + t := time.AfterFunc(d, func() { + f() + }) + return t +}