2008-12-03 17:40:00 -07:00
|
|
|
// Copyright 2009 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2009-08-12 14:18:37 -06:00
|
|
|
package time_test
|
2008-12-03 17:40:00 -07:00
|
|
|
|
|
|
|
import (
|
2009-12-15 16:41:46 -07:00
|
|
|
"testing"
|
|
|
|
. "time"
|
2008-12-03 17:40:00 -07:00
|
|
|
)
|
|
|
|
|
2009-09-23 14:02:14 -06:00
|
|
|
func TestTicker(t *testing.T) {
|
2012-02-14 14:13:19 -07:00
|
|
|
const Count = 10
|
|
|
|
Delta := 100 * Millisecond
|
|
|
|
if testing.Short() {
|
|
|
|
Delta = 10 * Millisecond
|
|
|
|
}
|
2009-12-15 16:41:46 -07:00
|
|
|
ticker := NewTicker(Delta)
|
2011-11-30 09:59:44 -07:00
|
|
|
t0 := Now()
|
2008-12-03 17:40:00 -07:00
|
|
|
for i := 0; i < Count; i++ {
|
2009-11-09 13:07:39 -07:00
|
|
|
<-ticker.C
|
2008-12-03 17:40:00 -07:00
|
|
|
}
|
2009-12-15 16:41:46 -07:00
|
|
|
ticker.Stop()
|
2011-11-30 09:59:44 -07:00
|
|
|
t1 := Now()
|
|
|
|
dt := t1.Sub(t0)
|
|
|
|
target := Delta * Count
|
2009-12-15 16:41:46 -07:00
|
|
|
slop := target * 2 / 10
|
2011-11-30 09:59:44 -07:00
|
|
|
if dt < target-slop || dt > target+slop {
|
|
|
|
t.Fatalf("%d %s ticks took %s, expected [%s,%s]", Count, Delta, dt, target-slop, target+slop)
|
2008-12-03 17:40:00 -07:00
|
|
|
}
|
2009-09-23 14:02:14 -06:00
|
|
|
// Now test that the ticker stopped
|
2009-12-15 16:41:46 -07:00
|
|
|
Sleep(2 * Delta)
|
2011-01-31 16:36:28 -07:00
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
2010-12-07 14:42:54 -07:00
|
|
|
t.Fatal("Ticker did not shut down")
|
2011-01-31 16:36:28 -07:00
|
|
|
default:
|
|
|
|
// ok
|
2009-09-23 14:02:14 -06:00
|
|
|
}
|
2008-12-03 17:40:00 -07:00
|
|
|
}
|
2010-02-17 15:55:29 -07:00
|
|
|
|
|
|
|
// Test that a bug tearing down a ticker has been fixed. This routine should not deadlock.
|
|
|
|
func TestTeardown(t *testing.T) {
|
2012-02-14 14:13:19 -07:00
|
|
|
Delta := 100 * Millisecond
|
|
|
|
if testing.Short() {
|
|
|
|
Delta = 20 * Millisecond
|
|
|
|
}
|
2010-02-17 15:55:29 -07:00
|
|
|
for i := 0; i < 3; i++ {
|
2012-02-14 14:13:19 -07:00
|
|
|
ticker := NewTicker(Delta)
|
2010-02-17 15:55:29 -07:00
|
|
|
<-ticker.C
|
|
|
|
ticker.Stop()
|
|
|
|
}
|
|
|
|
}
|
2011-01-25 13:25:48 -07:00
|
|
|
|
|
|
|
func BenchmarkTicker(b *testing.B) {
|
|
|
|
ticker := NewTicker(1)
|
|
|
|
b.ResetTimer()
|
|
|
|
b.StartTimer()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
<-ticker.C
|
|
|
|
}
|
|
|
|
b.StopTimer()
|
|
|
|
ticker.Stop()
|
|
|
|
}
|