本文整理汇总了Golang中Time.After函数的典型用法代码示例。如果您正苦于以下问题:Golang After函数的具体用法?Golang After怎么用?Golang After使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了After函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestEventerOnce
func TestEventerOnce(t *testing.T) {
e := NewEventer()
e.AddEvent("test")
sem := make(chan bool)
e.Once("test", func(data interface{}) {
sem <- true
})
go func() {
e.Publish("test", true)
}()
select {
case <-sem:
case <-time.After(10 * time.Millisecond):
t.Errorf("Once was not called")
}
go func() {
e.Publish("test", true)
}()
select {
case <-sem:
t.Errorf("Once was called twice")
case <-time.After(10 * time.Millisecond):
}
}
示例2: mapTestConcurrent2
func mapTestConcurrent2(size int, threads int) int64 {
//channel for getting times
done := make(chan int64, 2*threads)
var funcTimes int64 = 0
start := time.Now().UnixNano()
cMap := buildMapConcurrent2(size, threads, done)
mapReadTestConcurrent(cMap, threads, done)
i := 0
for t := range done {
funcTimes += t
i++
if i == 2*threads { //means I've read all of the values that will be read
close(done)
}
}
end := time.Now().UnixNano()
fmt.Println("V2: Concurrent Test:", float64((end-start))/1000000, "ms")
//fmt.Println("Concurrent Test additive", (funcTimes)/1000, "us")
<-time.After(time.Second * 3)
cMap.DestructMap()
<-time.After(time.Second * 2)
return end - start
}
示例3: testWatchCancelRunning
func testWatchCancelRunning(t *testing.T, wctx *watchctx) {
ctx, cancel := context.WithCancel(context.Background())
if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
t.Fatalf("expected non-nil watcher channel")
}
if _, err := wctx.kv.Put(ctx, "a", "a"); err != nil {
t.Fatal(err)
}
cancel()
select {
case <-time.After(time.Second):
t.Fatalf("took too long to cancel")
case v, ok := <-wctx.ch:
if !ok {
// closed before getting put; OK
break
}
// got the PUT; should close next
select {
case <-time.After(time.Second):
t.Fatalf("took too long to close")
case v, ok = <-wctx.ch:
if ok {
t.Fatalf("expected watcher channel to close, got %v", v)
}
}
}
}
示例4: main
func main() {
{
errChan := make(chan error)
go func() {
errChan <- nil
}()
select {
case v := <-errChan:
fmt.Println("even if nil, it still receives", v)
case <-time.After(time.Second):
fmt.Println("time-out!")
}
// even if nil, it still receives <nil>
}
{
errChan := make(chan error)
errChan = nil
go func() {
errChan <- nil
}()
select {
case v := <-errChan:
fmt.Println("even if nil, it still receives", v)
case <-time.After(time.Second):
fmt.Println("time-out!")
}
// time-out!
}
}
示例5: _TestReSeek
func _TestReSeek(_t *testing.T, poll bool) {
var name string
if poll {
name = "reseek-polling"
} else {
name = "reseek-inotify"
}
t := NewTailTest(name, _t)
t.CreateFile("test.txt", "a really long string goes here\nhello\nworld\n")
tail := t.StartTail(
"test.txt",
Config{Follow: true, ReOpen: true, Poll: poll, Location: -1})
go t.VerifyTailOutput(tail, []string{
"a really long string goes here", "hello", "world", "h311o", "w0r1d", "endofworld"})
// truncate now
<-time.After(100 * time.Millisecond)
t.TruncateFile("test.txt", "h311o\nw0r1d\nendofworld\n")
// Delete after a reasonable delay, to give tail sufficient time
// to read all lines.
<-time.After(100 * time.Millisecond)
t.RemoveFile("test.txt")
// Do not bother with stopping as it could kill the tomb during
// the reading of data written above. Timings can vary based on
// test environment.
// tail.Stop()
}
示例6: TestConnHandler
func TestConnHandler(t *testing.T) {
// t.Skip("skipping for another test")
t.Parallel()
ctx := context.Background()
swarms := makeSwarms(ctx, t, 5)
gotconn := make(chan struct{}, 10)
swarms[0].SetConnHandler(func(conn *Conn) {
gotconn <- struct{}{}
})
connectSwarms(t, ctx, swarms)
<-time.After(time.Millisecond)
// should've gotten 5 by now.
swarms[0].SetConnHandler(nil)
expect := 4
for i := 0; i < expect; i++ {
select {
case <-time.After(time.Second):
t.Fatal("failed to get connections")
case <-gotconn:
}
}
select {
case <-gotconn:
t.Fatalf("should have connected to %d swarms", expect)
default:
}
}
示例7: TestStrictOrdering
func (s *ConsumerSuite) TestStrictOrdering(c *C) {
// Test that we can strict ordering semantics
s.cn.options.StrictOrdering = true
s.Produce("test16", 0, "m1", "m2", "m3", "m4")
s.Produce("test16", 1, "m1", "m2", "m3", "m4")
c.Assert(s.cn.tryClaimPartition(0), Equals, true)
c.Assert(s.cn.tryClaimPartition(1), Equals, true)
c.Assert(s.m.waitForRsteps(4), Equals, 4)
msg1 := <-s.cn.messages
c.Assert(msg1.Value, DeepEquals, []byte("m1"))
msg2 := <-s.cn.messages
c.Assert(msg2.Value, DeepEquals, []byte("m1"))
// This should time out (no messages available)
select {
case <-s.cn.messages:
c.Error("Expected timeout, got message.")
case <-time.After(300 * time.Millisecond):
// Nothing, this is good.
}
// Commit the first message, expect a single new message
c.Assert(s.cn.Commit(msg1), IsNil)
msg3 := <-s.cn.messages
c.Assert(msg3.Value, DeepEquals, []byte("m2"))
// This should time out (no messages available)
select {
case <-s.cn.messages:
c.Error("Expected timeout, got message.")
case <-time.After(300 * time.Millisecond):
// Nothing, this is good.
}
}
示例8: TestBulkSmallBatch
func TestBulkSmallBatch(t *testing.T) {
InitTests(true)
c := NewTestConn()
date := time.Unix(1257894000, 0)
data := map[string]interface{}{"name": "smurfs", "age": 22, "date": time.Unix(1257894000, 0)}
// Now tests small batches
indexer := c.NewBulkIndexer(1)
indexer.BufferDelayMax = 100 * time.Millisecond
indexer.BulkMaxDocs = 2
messageSets = 0
indexer.Sender = func(buf *bytes.Buffer) error {
messageSets += 1
return indexer.Send(buf)
}
indexer.Start()
<-time.After(time.Millisecond * 20)
indexer.Index("users", "user", "2", "", &date, data, true)
indexer.Index("users", "user", "3", "", &date, data, true)
indexer.Index("users", "user", "4", "", &date, data, true)
<-time.After(time.Millisecond * 200)
// indexer.Flush()
indexer.Stop()
assert.T(t, messageSets == 2, fmt.Sprintf("Should have sent 2 message sets %d", messageSets))
}
示例9: TestCloseClosesAllConnections
func (t *PoolTest) TestCloseClosesAllConnections(c *C) {
ln, err := t.db.Listen("test_channel")
c.Assert(err, IsNil)
wait := make(chan struct{}, 2)
go func() {
wait <- struct{}{}
_, _, err := ln.Receive()
c.Assert(err, ErrorMatches, `^(.*use of closed network connection|EOF)$`)
wait <- struct{}{}
}()
select {
case <-wait:
// ok
case <-time.After(3 * time.Second):
c.Fatal("timeout")
}
c.Assert(t.db.Close(), IsNil)
select {
case <-wait:
// ok
case <-time.After(3 * time.Second):
c.Fatal("timeout")
}
c.Assert(t.db.Pool().Len(), Equals, 0)
c.Assert(t.db.Pool().FreeLen(), Equals, 0)
}
示例10: waitForWellFormedTables
// if minPeers or avgPeers is 0, dont test for it.
func waitForWellFormedTables(t *testing.T, dhts []*IpfsDHT, minPeers, avgPeers int, timeout time.Duration) bool {
// test "well-formed-ness" (>= minPeers peers in every routing table)
checkTables := func() bool {
totalPeers := 0
for _, dht := range dhts {
rtlen := dht.routingTable.Size()
totalPeers += rtlen
if minPeers > 0 && rtlen < minPeers {
t.Logf("routing table for %s only has %d peers (should have >%d)", dht.self, rtlen, minPeers)
return false
}
}
actualAvgPeers := totalPeers / len(dhts)
t.Logf("avg rt size: %d", actualAvgPeers)
if avgPeers > 0 && actualAvgPeers < avgPeers {
t.Logf("avg rt size: %d < %d", actualAvgPeers, avgPeers)
return false
}
return true
}
timeoutA := time.After(timeout)
for {
select {
case <-timeoutA:
log.Debugf("did not reach well-formed routing tables by %s", timeout)
return false // failed
case <-time.After(5 * time.Millisecond):
if checkTables() {
return true // succeeded
}
}
}
}
示例11: TestCustomDialNew
func (s *S) TestCustomDialNew(c *C) {
dials := make(chan bool, 16)
dial := func(addr *mgo.ServerAddr) (net.Conn, error) {
dials <- true
if addr.TCPAddr().Port == 40012 {
c.Check(addr.String(), Equals, "localhost:40012")
}
return net.DialTCP("tcp", nil, addr.TCPAddr())
}
info := mgo.DialInfo{
Addrs: []string{"localhost:40012"},
DialServer: dial,
}
// Use hostname here rather than IP, to make things trickier.
session, err := mgo.DialWithInfo(&info)
c.Assert(err, IsNil)
defer session.Close()
const N = 3
for i := 0; i < N; i++ {
select {
case <-dials:
case <-time.After(5 * time.Second):
c.Fatalf("expected %d dials, got %d", N, i)
}
}
select {
case <-dials:
c.Fatalf("got more dials than expected")
case <-time.After(100 * time.Millisecond):
}
}
示例12: Run
// Run is the main republisher loop
func (np *Republisher) Run() {
for {
select {
case <-np.Publish:
quick := time.After(np.TimeoutShort)
longer := time.After(np.TimeoutLong)
wait:
var pubnowresp chan struct{}
select {
case <-np.ctx.Done():
return
case <-np.Publish:
quick = time.After(np.TimeoutShort)
goto wait
case <-quick:
case <-longer:
case pubnowresp = <-np.pubnowch:
}
err := np.publish(np.ctx)
if pubnowresp != nil {
pubnowresp <- struct{}{}
}
if err != nil {
log.Errorf("republishRoot error: %s", err)
}
case <-np.ctx.Done():
return
}
}
}
示例13: testSeqNoWait
func testSeqNoWait(t *testing.T, toTest intervalFunc) {
t.Parallel()
last := time.Now()
times := make(chan time.Time, 10)
wait := make(chan struct{})
p := toTest(times, wait)
for i := 0; i < 5; i++ {
next := <-times
testBetween(t, 0, next.Sub(last), interval+grace) // min of 0
<-time.After(interval * 2) // make it wait.
last = time.Now() // make it now (sequential)
wait <- struct{}{} // release it.
}
go p.Close()
end:
select {
case wait <- struct{}{}: // drain any extras.
goto end
case <-p.Closed():
case <-time.After(timeout):
t.Error("proc failed to close")
}
}
示例14: TestWritePostCancel
func TestWritePostCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
piper, pipew := io.Pipe()
w := NewWriter(ctx, pipew)
buf := []byte("abcdefghij")
buf2 := make([]byte, 10)
done := make(chan ioret)
go func() {
n, err := w.Write(buf)
done <- ioret{n, err}
}()
piper.Read(buf2)
select {
case ret := <-done:
if ret.n != 10 {
t.Error("ret.n should be 10", ret.n)
}
if ret.err != nil {
t.Error("ret.err should be nil", ret.err)
}
if string(buf2) != "abcdefghij" {
t.Error("write contents differ")
}
case <-time.After(20 * time.Millisecond):
t.Fatal("failed to write")
}
go func() {
n, err := w.Write(buf)
done <- ioret{n, err}
}()
cancel()
select {
case ret := <-done:
if ret.n != 0 {
t.Error("ret.n should be 0", ret.n)
}
if ret.err == nil {
t.Error("ret.err should be ctx error", ret.err)
}
case <-time.After(20 * time.Millisecond):
t.Fatal("failed to stop writing after cancel")
}
copy(buf, []byte("aaaaaaaaaa"))
piper.Read(buf2)
if string(buf2) == "aaaaaaaaaa" {
t.Error("buffer was read from after ctx cancel")
} else if string(buf2) != "abcdefghij" {
t.Error("write contents differ from expected")
}
}
示例15: TestRateLimiting
func TestRateLimiting(_t *testing.T) {
t := NewTailTest("rate-limiting", _t)
t.CreateFile("test.txt", "hello\nworld\nagain\nextra\n")
config := Config{
Follow: true,
RateLimiter: ratelimiter.NewLeakyBucket(2, time.Second)}
leakybucketFull := "Too much log activity; waiting a second before resuming tailing"
tail := t.StartTail("test.txt", config)
// TODO: also verify that tail resumes after the cooloff period.
go t.VerifyTailOutput(tail, []string{
"hello", "world", "again",
leakybucketFull,
"more", "data",
leakybucketFull})
// Add more data only after reasonable delay.
<-time.After(1200 * time.Millisecond)
t.AppendFile("test.txt", "more\ndata\n")
// Delete after a reasonable delay, to give tail sufficient time
// to read all lines.
<-time.After(100 * time.Millisecond)
t.RemoveFile("test.txt")
// tail.Stop()
tail.Cleanup()
}