Skip to content

Commit

Permalink
chore: clean up code and add test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
fufuok committed Dec 1, 2024
1 parent 17794bf commit a4a113b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
11 changes: 3 additions & 8 deletions master/ntpdate.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,15 @@ var (
ntpCancel context.CancelFunc
ntpName string

ntpFirstDone = false
ntpFirstDoneChan = make(chan struct{}, 1)
ntpFirstDoneChan = make(chan struct{})
)

// WaitUntilNtpdate 等待, 直到第一次时间同步成功
func WaitUntilNtpdate(timeout time.Duration) bool {
if ntpFirstDone {
return true
}

select {
case <-time.After(timeout):
return false
case <-ntpFirstDoneChan:
ntpFirstDone = true
return true
}
}
Expand Down Expand Up @@ -78,7 +72,8 @@ func ntpdate() {
ntpCancel()
common.SetClockOffset(dur)

ntpFirstDoneChan <- struct{}{}
// 首次时间同步完成
close(ntpFirstDoneChan)

// 定时同步
ntpCtx, ntpCancel = context.WithCancel(context.Background())
Expand Down
21 changes: 21 additions & 0 deletions master/ntpdate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package master

import (
"testing"
"time"

"github.com/fufuok/utils/assert"
)

func TestWaitUntilNtpdate(t *testing.T) {
go func() {
time.Sleep(100 * time.Millisecond)
close(ntpFirstDoneChan)
}()
assert.False(t, WaitUntilNtpdate(50*time.Millisecond))
assert.True(t, WaitUntilNtpdate(120*time.Millisecond))
assert.True(t, WaitUntilNtpdate(120*time.Millisecond))
time.Sleep(100 * time.Millisecond)
assert.True(t, WaitUntilNtpdate(50*time.Millisecond))
assert.True(t, WaitUntilNtpdate(500*time.Millisecond))
}

0 comments on commit a4a113b

Please sign in to comment.