本文整理汇总了Golang中Time.AfterFunc函数的典型用法代码示例。如果您正苦于以下问题:Golang AfterFunc函数的具体用法?Golang AfterFunc怎么用?Golang AfterFunc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了AfterFunc函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestVirtualBoxBuildAbort
func TestVirtualBoxBuildAbort(t *testing.T) {
if helpers.SkipIntegrationTests(t, vboxManage, "--version") {
return
}
build := &common.Build{
GetBuildResponse: common.LongRunningBuild,
Runner: &common.RunnerConfig{
RunnerSettings: common.RunnerSettings{
Executor: "virtualbox",
VirtualBox: &common.VirtualBoxConfig{
BaseName: vboxImage,
DisableSnapshots: true,
},
SSH: vboxSshConfig,
},
},
SystemInterrupt: make(chan os.Signal, 1),
}
abortTimer := time.AfterFunc(time.Second, func() {
t.Log("Interrupt")
build.SystemInterrupt <- os.Interrupt
})
defer abortTimer.Stop()
timeoutTimer := time.AfterFunc(time.Minute, func() {
t.Log("Timedout")
t.FailNow()
})
defer timeoutTimer.Stop()
err := build.Run(&common.Config{}, &common.Trace{Writer: os.Stdout})
assert.EqualError(t, err, "aborted: interrupt")
}
示例2: TestDockerCommandBuildAbort
func TestDockerCommandBuildAbort(t *testing.T) {
if helpers.SkipIntegrationTests(t, "docker", "info") {
return
}
build := &common.Build{
GetBuildResponse: common.LongRunningBuild,
Runner: &common.RunnerConfig{
RunnerSettings: common.RunnerSettings{
Executor: "docker",
Docker: &common.DockerConfig{
Image: "alpine",
},
},
},
SystemInterrupt: make(chan os.Signal, 1),
}
abortTimer := time.AfterFunc(time.Second, func() {
t.Log("Interrupt")
build.SystemInterrupt <- os.Interrupt
})
defer abortTimer.Stop()
timeoutTimer := time.AfterFunc(time.Minute, func() {
t.Log("Timedout")
t.FailNow()
})
defer timeoutTimer.Stop()
err := build.Run(&common.Config{}, &common.Trace{Writer: os.Stdout})
assert.EqualError(t, err, "aborted: interrupt")
}
示例3: TestParseXML
func (s *StreamSuite) TestParseXML(c *C) {
log.Println("testing ParseXML")
b, ch := newBlock("testingParseXML", "parsexml")
go blocks.BlockRoutine(b)
outChan := make(chan *blocks.Msg)
ch.AddChan <- &blocks.AddChanMsg{
Route: "out",
Channel: outChan,
}
// where to find the xml in input
ruleMsg := map[string]interface{}{"Path": ".data"}
toRule := &blocks.Msg{Msg: ruleMsg, Route: "rule"}
ch.InChan <- toRule
queryOutChan := make(chan interface{})
time.AfterFunc(time.Duration(1)*time.Second, func() {
ch.QueryChan <- &blocks.QueryMsg{RespChan: queryOutChan, Route: "rule"}
})
var xmldata = string(`
<?xml version="1.0" encoding="utf-8"?>
<OdfBody DocumentType="DT_GM" Date="20130131" Time="140807885" LogicalDate="20130131" Venue="ACV" Language="ENG" FeedFlag="P" DocumentCode="AS0ACV000" Version="3" Serial="1">
<Competition Code="OG2014">
<Config SDelay="60" />
</Competition>
</OdfBody>
`)
time.AfterFunc(time.Duration(2)*time.Second, func() {
xmlMsg := map[string]interface{}{"data": xmldata}
postData := &blocks.Msg{Msg: xmlMsg, Route: "in"}
ch.InChan <- postData
})
time.AfterFunc(time.Duration(5)*time.Second, func() {
ch.QuitChan <- true
})
for {
select {
case err := <-ch.ErrChan:
if err != nil {
c.Errorf(err.Error())
} else {
return
}
case messageI := <-queryOutChan:
if !reflect.DeepEqual(messageI, ruleMsg) {
log.Println("Rule mismatch:", messageI, ruleMsg)
c.Fail()
}
case messageI := <-outChan:
message := messageI.Msg.(map[string]interface{})
odfbody := message["OdfBody"].(map[string]interface{})
competition := odfbody["Competition"].(map[string]interface{})
c.Assert(odfbody["DocumentType"], Equals, "DT_GM")
c.Assert(competition["Code"], Equals, "OG2014")
}
}
}
示例4: RoundTrip
func (ctx *requestCtx) RoundTrip() {
defer func() {
ctx.hasPrint = true
ctx.SetLog("logType", "defer")
ctx.PrintLog()
}()
time.AfterFunc(10*time.Second, func() {
if !ctx.hasPrint {
ctx.SetLog("logType", "timeout10")
ctx.PrintLog()
}
})
removeHeader(ctx.Req)
rewrite_code := ctx.ser.reqRewrite(ctx)
ctx.HasBroadcast = ctx.ser.Broadcast_Req(ctx)
ctx.SetLog("js_rewrite_code", rewrite_code)
time.AfterFunc(1*time.Second, ctx.saveRequestData)
if rewrite_code != 200 && rewrite_code != 304 {
ctx.badGateway(fmt.Errorf("rewrite failed"))
return
}
ctx.ser.proxy.RoundTrip(ctx)
}
示例5: handleFailedConn
// handleFailedConn handles a connection failed due to a disconnect or any
// other failure. If permanent, it retries the connection after the configured
// retry duration. Otherwise, if required, it makes a new connection request.
// After maxFailedConnectionAttempts new connections will be retried after the
// configured retry duration.
func (cm *ConnManager) handleFailedConn(c *ConnReq) {
if atomic.LoadInt32(&cm.stop) != 0 {
return
}
if c.Permanent {
c.retryCount++
d := time.Duration(c.retryCount) * cm.cfg.RetryDuration
if d > maxRetryDuration {
d = maxRetryDuration
}
log.Debugf("Retrying connection to %v in %v", c, d)
time.AfterFunc(d, func() {
cm.Connect(c)
})
} else if cm.cfg.GetNewAddress != nil {
cm.failedAttempts++
if cm.failedAttempts >= maxFailedAttempts {
log.Debugf("Max failed connection attempts reached: [%d] "+
"-- retrying connection in: %v", maxFailedAttempts,
cm.cfg.RetryDuration)
time.AfterFunc(cm.cfg.RetryDuration, func() {
cm.NewConnReq()
})
} else {
go cm.NewConnReq()
}
}
}
示例6: Send
// Create Client transaction.
func (mng *Manager) Send(r *base.Request, dest string) *ClientTransaction {
log.Debug("Sending to %v: %v", dest, r.String())
tx := &ClientTransaction{}
tx.origin = r
tx.dest = dest
tx.transport = mng.transport
tx.tm = mng
tx.initFSM()
tx.tu = make(chan *base.Response, 3)
tx.tu_err = make(chan error, 1)
tx.timer_a_time = T1
tx.timer_a = time.AfterFunc(tx.timer_a_time, func() {
tx.fsm.Spin(client_input_timer_a)
})
tx.timer_b = time.AfterFunc(64*T1, func() {
tx.fsm.Spin(client_input_timer_b)
})
// Timer D is set to 32 seconds for unreliable transports, and 0 seconds otherwise.
tx.timer_d_time = 32 * time.Second
err := mng.transport.Send(dest, r)
if err != nil {
log.Warn("Failed to send message: %s", err.Error())
tx.fsm.Spin(client_input_transport_err)
}
mng.putTx(tx)
return tx
}
示例7: backoff
func (r *Consumer) backoff() {
if atomic.LoadInt32(&r.stopFlag) == 1 {
atomic.StoreInt64(&r.backoffDuration, 0)
return
}
// pick a random connection to test the waters
conns := r.conns()
if len(conns) == 0 {
// backoff again
backoffDuration := 1 * time.Second
atomic.StoreInt64(&r.backoffDuration, backoffDuration.Nanoseconds())
time.AfterFunc(backoffDuration, r.backoff)
return
}
idx := r.rng.Intn(len(conns))
choice := conns[idx]
r.log(LogLevelWarning,
"(%s) backoff timeout expired, sending RDY 1",
choice.String())
// while in backoff only ever let 1 message at a time through
err := r.updateRDY(choice, 1)
if err != nil {
r.log(LogLevelWarning, "(%s) error updating RDY - %s", choice.String(), err)
backoffDuration := 1 * time.Second
atomic.StoreInt64(&r.backoffDuration, backoffDuration.Nanoseconds())
time.AfterFunc(backoffDuration, r.backoff)
return
}
atomic.StoreInt64(&r.backoffDuration, 0)
}
示例8: TestDockerCommandBuildCancel
func TestDockerCommandBuildCancel(t *testing.T) {
if helpers.SkipIntegrationTests(t, "docker", "info") {
return
}
build := &common.Build{
GetBuildResponse: common.LongRunningBuild,
Runner: &common.RunnerConfig{
RunnerSettings: common.RunnerSettings{
Executor: "docker",
Docker: &common.DockerConfig{
Image: "alpine",
},
},
},
}
trace := &common.Trace{Writer: os.Stdout, Abort: make(chan interface{}, 1)}
abortTimer := time.AfterFunc(time.Second, func() {
t.Log("Interrupt")
trace.Abort <- true
})
defer abortTimer.Stop()
timeoutTimer := time.AfterFunc(time.Minute, func() {
t.Log("Timedout")
t.FailNow()
})
defer timeoutTimer.Stop()
err := build.Run(&common.Config{}, trace)
assert.IsType(t, err, &common.BuildError{})
assert.EqualError(t, err, "canceled")
}
示例9: TestCanStartAndStopBeat
func TestCanStartAndStopBeat(t *testing.T) {
ab, b := newBeat("throttle_test.yml", nil)
stopped := make(chan bool)
killed := make(chan bool)
time.AfterFunc(5*time.Second, func() {
killed <- true
close(killed)
})
time.AfterFunc(500*time.Millisecond, func() {
ab.Stop()
})
go func() {
ab.Run(b)
stopped <- true
close(stopped)
}()
select {
case <-stopped:
case <-killed:
t.Error("Failed to stop beat in test. Ctrl+C may be necessary..")
}
}
示例10: renewLoop
func (t *TokenRenewer) renewLoop() {
t.renewLoopWG.Add(1)
defer t.renewLoopWG.Done()
// renews token before it expires (sends the first signal to the goroutine below)
go time.AfterFunc(t.renewDuration(), t.sendRenewTokenSignal)
// renew token on signal util remote kite disconnects.
for {
select {
case <-t.signalRenewToken:
switch err := t.renewToken(); {
case err == nil:
go time.AfterFunc(t.renewDuration(), t.sendRenewTokenSignal)
case err == ErrNoKitesAvailable || strings.Contains(err.Error(), "no kites found"):
// If kite went down we're not going to renew the token,
// as we need to dial either way.
//
// This case handles a situation, when kite missed
// disconnect signal (observed to happen with XHR transport).
default:
t.localKite.Log.Error("token renewer: %s Cannot renew token for Kite: %s I will retry in %d seconds...",
err, t.client.ID, retryInterval/time.Second)
// Need to sleep here litle bit because a signal is sent
// when an expired token is detected on incoming request.
// This sleep prevents the signal from coming too fast.
time.Sleep(1 * time.Second)
go time.AfterFunc(retryInterval, t.sendRenewTokenSignal)
}
case <-t.disconnect:
return
}
}
}
示例11: ExampleContextRelationShip
func ExampleContextRelationShip() {
ctx1, cancel1 := context.WithCancel(context.Background())
ctx2, cancel2 := context.WithCancel(ctx1)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
log.Printf("waiting for ctx1...")
<-ctx1.Done()
log.Printf("ctx1.Done() returns")
}()
go func() {
defer wg.Done()
log.Printf("waiting for ctx2....")
<-ctx2.Done()
log.Printf("ctx2.Done() returns")
}()
time.AfterFunc(time.Second*5, cancel2)
time.AfterFunc(time.Second*1, cancel1) //触发 1 2 同时结束
wg.Wait()
}
示例12: Command
// Command executes the named program with the given arguments. If it does not
// exit within timeout, it is sent SIGINT (if supported by Go). After
// another timeout, it is killed.
func Command(timeout time.Duration, stdin io.Reader, name string, arg ...string) (io.Reader, error) {
if _, err := exec.LookPath(name); err != nil {
return nil, ErrPath
}
if Debug {
slog.Infof("executing command: %v %v", name, arg)
}
c := exec.Command(name, arg...)
b := &bytes.Buffer{}
c.Stdout = b
c.Stdin = stdin
if err := c.Start(); err != nil {
return nil, err
}
timedOut := false
intTimer := time.AfterFunc(timeout, func() {
slog.Errorf("Process taking too long. Interrupting: %s %s", name, strings.Join(arg, " "))
c.Process.Signal(os.Interrupt)
timedOut = true
})
killTimer := time.AfterFunc(timeout*2, func() {
slog.Errorf("Process taking too long. Killing: %s %s", name, strings.Join(arg, " "))
c.Process.Signal(os.Kill)
timedOut = true
})
err := c.Wait()
intTimer.Stop()
killTimer.Stop()
if timedOut {
return nil, ErrTimeout
}
return b, err
}
示例13: FinalSave
// FinalSave should be called immediately before exiting, and only before
// exiting, in order to flush tasks to disk. It waits a short timeout for state
// to settle if necessary. If unable to reach a steady-state and save within
// this short timeout, it returns an error
func FinalSave(saver statemanager.Saver, taskEngine engine.TaskEngine) error {
engineDisabled := make(chan error)
disableTimer := time.AfterFunc(engineDisableTimeout, func() {
engineDisabled <- errors.New("Timed out waiting for TaskEngine to settle")
})
go func() {
log.Debug("Shutting down task engine")
taskEngine.Disable()
disableTimer.Stop()
engineDisabled <- nil
}()
disableErr := <-engineDisabled
stateSaved := make(chan error)
saveTimer := time.AfterFunc(finalSaveTimeout, func() {
stateSaved <- errors.New("Timed out trying to save to disk")
})
go func() {
log.Debug("Saving state before shutting down")
stateSaved <- saver.ForceSave()
saveTimer.Stop()
}()
saveErr := <-stateSaved
if disableErr != nil || saveErr != nil {
return utils.NewMultiError(disableErr, saveErr)
}
return nil
}
示例14: doActions
func (rn *RaftNode) doActions(actions []Action) {
for _, action := range actions {
switch action.(type) {
case Send:
//resetting the timer
rn.timer.Stop()
rn.timer = time.AfterFunc(time.Duration(1000+rand.Intn(400))*time.Millisecond, func() { rn.timeoutCh <- Timeout{} })
actionname := action.(Send)
rn.serverOfCluster.Outbox() <- &cluster.Envelope{Pid: actionname.To, Msg: actionname.Event}
case Alarm:
//resetting the timer
rn.timer.Stop()
rn.timer = time.AfterFunc(time.Duration(1000+rand.Intn(400))*time.Millisecond, func() { rn.timeoutCh <- Timeout{} })
case Commit:
//output commit obtained from statemachine into the Commit Channel
newaction := action.(Commit)
rn.CommitChannel() <- &newaction
case LogStore:
//creating persistent log files
lg, _ := log.Open(rn.LogDir + string(rn.server.MyID))
logstore := action.(LogStore)
lg.Append(logstore.Data)
case StateStore:
//creating files for persistent storage of State
statestore := action.(StateStore)
//writing statestore into the persistent storage
err := writeFile("statestore"+strconv.Itoa(rn.server.MyID), statestore)
if err != nil {
//reading from the persistent storage
_, err := readFile("statestore" + strconv.Itoa(rn.server.MyID))
if err != nil {
}
}
}
}
}
示例15: testJobWithGracelessSuspendResume
func testJobWithGracelessSuspendResume() {
job1, _ := grid.CreateJob(&grid.JobDefinition{ID: "job1", Cmd: "", Data: []interface{}{1, 3, 5, 7, 9, 11, 13, 15, 17},
Description: "", Ctx: &grid.Context{"foo": "bar"},
Ctrl: &grid.JobControl{MaxConcurrency: 0}})
time.AfterFunc(300*time.Millisecond, func() { fmt.Println("suspending job", job1); grid.SuspendJob(job1, false) })
time.AfterFunc(3*time.Second, func() { fmt.Println("resuming job", job1); grid.RetryJob(job1) })
simulate(7, []grid.JobID{job1})
}