本文整理汇总了Golang中Time.Timer.Reset方法的典型用法代码示例。如果您正苦于以下问题:Golang Timer.Reset方法的具体用法?Golang Timer.Reset怎么用?Golang Timer.Reset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Time.Timer
的用法示例。
在下文中一共展示了Timer.Reset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
broker := NewBroker()
port, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
if len(os.Args) > 2 {
registryURL := os.Args[2]
myURL := os.Args[3]
err := announceBroker(registryURL, myURL)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
var timer *time.Timer
timer = time.AfterFunc(RegistryAnnouncePeriod, func() {
err := announceBroker(registryURL, myURL)
if err != nil {
fmt.Println("Error reannouncing to broker!")
}
timer.Reset(RegistryAnnouncePeriod)
})
}
http.Handle("/", broker)
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
示例2: established
func (h *FSMHandler) established() bgp.FSMState {
fsm := h.fsm
h.conn = fsm.conn
h.t.Go(h.sendMessageloop)
h.msgCh = h.incoming
h.t.Go(h.recvMessageloop)
var holdTimer *time.Timer
if fsm.negotiatedHoldTime == 0 {
holdTimer = &time.Timer{}
} else {
holdTimer = time.NewTimer(time.Second * time.Duration(fsm.negotiatedHoldTime))
}
for {
select {
case <-h.t.Dying():
return 0
case conn, ok := <-fsm.connCh:
if !ok {
break
}
conn.Close()
log.WithFields(log.Fields{
"Topic": "Peer",
"Key": fsm.peerConfig.NeighborAddress,
}).Warn("Closed an accepted connection")
case <-h.errorCh:
h.conn.Close()
h.t.Kill(nil)
h.reason = "Peer closed the session"
return bgp.BGP_FSM_IDLE
case <-holdTimer.C:
log.WithFields(log.Fields{
"Topic": "Peer",
"Key": fsm.peerConfig.NeighborAddress,
"data": bgp.BGP_FSM_ESTABLISHED,
}).Warn("hold timer expired")
m := bgp.NewBGPNotificationMessage(bgp.BGP_ERROR_HOLD_TIMER_EXPIRED, 0, nil)
h.outgoing <- m
h.reason = "HoldTimer expired"
return bgp.BGP_FSM_IDLE
case <-h.holdTimerResetCh:
if fsm.negotiatedHoldTime != 0 {
holdTimer.Reset(time.Second * time.Duration(fsm.negotiatedHoldTime))
}
case s := <-fsm.adminStateCh:
err := h.changeAdminState(s)
if err == nil {
switch s {
case ADMIN_STATE_DOWN:
m := bgp.NewBGPNotificationMessage(
bgp.BGP_ERROR_CEASE, bgp.BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN, nil)
h.outgoing <- m
}
}
}
}
return 0
}
示例3: timedDecoder
// timedDecoder returns a Decorated decoder that generates the given error if no events
// are decoded for some number of sequential timeouts. The returned Decoder is not safe
// to share across goroutines.
// TODO(jdef) this probably isn't the right place for all of this logic (and it's not
// just monitoring the heartbeat messages, it's counting all of them..). Heartbeat monitoring
// has specific requirements. Get rid of this and implement something better elsewhere.
func timedDecoder(dec records.Decoder, dur time.Duration, timeouts int, err error) records.Decoder {
var t *time.Timer
return records.DecoderFunc(func(v interface{}) error {
if t == nil {
t = time.NewTimer(dur)
} else {
t.Reset(dur)
}
defer t.Stop()
errCh := make(chan error, 1)
go func() {
// there's no way to abort this so someone else will have
// to make sure that it dies (and it should if the response
// body is closed)
errCh <- dec.Decode(v)
}()
for x := 0; x < timeouts; x++ {
select {
case <-t.C:
// check for a tie
select {
case e := <-errCh:
return e
default:
// noop, continue
}
case e := <-errCh:
return e
}
}
return err
})
}
示例4: doLater
// execute some action in the context of the current process. Actions
// executed via this func are to be executed in a concurrency-safe manner:
// no two actions should execute at the same time. invocations of this func
// should not block for very long, unless the action backlog is full or the
// process is terminating.
// returns errProcessTerminated if the process already ended.
func (self *procImpl) doLater(deferredAction Action) (err <-chan error) {
a := Action(func() {
self.wg.Add(1)
defer self.wg.Done()
deferredAction()
})
scheduled := false
self.writeLock.Lock()
defer self.writeLock.Unlock()
var timer *time.Timer
for err == nil && !scheduled {
switch s := self.state.get(); s {
case stateRunning:
select {
case self.backlog <- a:
scheduled = true
default:
if timer == nil {
timer = time.AfterFunc(self.maxRescheduleWait, self.changed.Broadcast)
} else {
timer.Reset(self.maxRescheduleWait)
}
self.changed.Wait()
timer.Stop()
}
case stateTerminal:
err = ErrorChan(errProcessTerminated)
default:
err = ErrorChan(errIllegalState)
}
}
return
}
示例5: internalPubAsync
func internalPubAsync(clientTimer *time.Timer, msgBody *bytes.Buffer, topic *nsqd.Topic) error {
if topic.Exiting() {
return nsqd.ErrExiting
}
info := &nsqd.PubInfo{
Done: make(chan struct{}),
MsgBody: msgBody,
StartPub: time.Now(),
}
if clientTimer == nil {
clientTimer = time.NewTimer(time.Second * 5)
} else {
clientTimer.Reset(time.Second * 5)
}
select {
case topic.GetWaitChan() <- info:
default:
select {
case topic.GetWaitChan() <- info:
case <-topic.QuitChan():
nsqd.NsqLogger().Infof("topic %v put messages failed at exiting", topic.GetFullName())
return nsqd.ErrExiting
case <-clientTimer.C:
nsqd.NsqLogger().Infof("topic %v put messages timeout ", topic.GetFullName())
return ErrPubToWaitTimeout
}
}
<-info.Done
return info.Err
}
示例6: appMain
func appMain(driver gxui.Driver) {
theme := dark.CreateTheme(driver)
label := theme.CreateLabel()
label.SetText("This is a progress bar:")
progressBar := theme.CreateProgressBar()
progressBar.SetDesiredSize(math.Size{W: 400, H: 20})
progressBar.SetTarget(100)
layout := theme.CreateLinearLayout()
layout.AddChild(label)
layout.AddChild(progressBar)
layout.SetHorizontalAlignment(gxui.AlignCenter)
window := theme.CreateWindow(800, 600, "Progress bar")
window.SetScale(flags.DefaultScaleFactor)
window.AddChild(layout)
window.OnClose(driver.Terminate)
progress := 0
pause := time.Millisecond * 500
var timer *time.Timer
timer = time.AfterFunc(pause, func() {
driver.Call(func() {
progress = (progress + 3) % progressBar.Target()
progressBar.SetProgress(progress)
timer.Reset(pause)
})
})
}
示例7: timerLoop
// timerLoop loops indefinitely to query the given API, until "wait" times
// out, using the "tick" timer to delay the API queries. It writes the
// result to the given output.
func timerLoop(api APIClient, requestedId string, wait, tick *time.Timer) (params.ActionResult, error) {
var (
result params.ActionResult
err error
)
// Loop over results until we get "failed" or "completed". Wait for
// timer, and reset it each time.
for {
result, err = fetchResult(api, requestedId)
if err != nil {
return result, err
}
// Whether or not we're waiting for a result, if a completed
// result arrives, we're done.
switch result.Status {
case params.ActionRunning, params.ActionPending:
default:
return result, nil
}
// Block until a tick happens, or the timeout arrives.
select {
case _ = <-wait.C:
return result, nil
case _ = <-tick.C:
tick.Reset(2 * time.Second)
}
}
}
示例8: runReader
func (s *Scheme) runReader(reader factory.Reader, timer *time.Timer) {
if s.warmupMessagesPerRun > 0 {
logs.Logger.Info("Reading %d warmup messages", s.warmupMessagesPerRun)
}
var startTime, lastMessageTime time.Time
buffer := make([]byte, s.bytesPerMessage*2)
for i := 0; i < s.warmupMessagesPerRun; i++ {
reader.Read(buffer)
}
logs.Logger.Info("Starting reading %d messages...", s.messagesPerRun)
for {
count, err := reader.Read(buffer)
if err == io.EOF {
break
}
lastMessageTime = time.Now()
if startTime.IsZero() {
startTime = lastMessageTime
}
timer.Reset(s.waitForLastMessage)
s.countMessage(count, err)
}
logs.Logger.Info("Finished.")
s.runTime = lastMessageTime.Sub(startTime)
}
示例9: advertiseTimer
func (s *Ssdp) advertiseTimer(ads *AdvertisableServer, d time.Duration, age int) *time.Timer {
var timer *time.Timer
timer = time.AfterFunc(d, func() {
s.advertiseServer(ads, true)
timer.Reset(d + time.Duration(age)*time.Second)
})
return timer
}
示例10: initTimer
func initTimer(t *time.Timer, timeout time.Duration) *time.Timer {
if t == nil {
return time.NewTimer(timeout)
}
if t.Reset(timeout) {
panic("BUG: active timer trapped into initTimer()")
}
return t
}
示例11: setTimer
func setTimer(timer *time.Timer, d time.Duration) *time.Timer {
if timer == nil {
return time.NewTimer(d)
}
timer.Reset(d)
return timer
}
示例12: main
func main() {
start := time.Now()
var t *time.Timer
t = time.AfterFunc(randomDuration(), func() {
fmt.Println(time.Now().Sub(start))
t.Reset(randomDuration())
})
time.Sleep(5 * time.Second)
}
示例13: run
func (a *Agent) run(ops <-chan opFunc) {
var timer *time.Timer
var retry <-chan time.Time
retryNeeded := false
a.ticker = time.NewTicker(a.Cycle)
defer a.ticker.Stop()
trySend := func(from time.Time) {
if err := a.sendRequest(from); err == nil {
retryNeeded = false
a.lastPoll = from
a.clear()
} else if iserr(err, errMustRetry) {
if timer == nil {
timer = time.NewTimer(time.Minute)
retry = timer.C
} else {
timer.Reset(time.Minute)
}
retryNeeded = true
} else {
a.err = err
}
}
for {
select {
case from := <-retry:
trySend(from)
case from := <-a.ticker.C:
if a.LogMetrics {
a.logMetrics()
}
if !retryNeeded {
// Let the retry loop take over until things are back to normal.
trySend(from)
}
case op, ok := <-ops:
if !ok {
return
} else if op == nil {
// This should be impossible. If it happens, log it and skip the op.
fmt.Fprintln(a.Log, ErrNilOpReceived)
continue
}
if err := op(a); iserr(err, errShuttingDown) {
return
} else if err != nil {
a.err = err
}
}
}
}
示例14: Handler
func Handler(in <-chan nog.Message, out chan<- nog.Message) {
out <- nog.Message{What: "started"}
s := &Motion{}
go func() {
out <- nog.Template("motion")
}()
var motionTimer *time.Timer
var motionTimeout <-chan time.Time
if c, err := gpio.GPIOInterrupt(7); err == nil {
s.motionChannel = c
} else {
log.Println("Warning: Motion sensor off:", err)
out <- nog.Message{What: "no motion sensor found"}
goto done
}
for {
select {
case m, ok := <-in:
if !ok {
goto done
}
if m.Why == "statechanged" {
dec := json.NewDecoder(strings.NewReader(m.What))
if err := dec.Decode(s); err != nil {
log.Println("motion decode err:", err)
}
}
case motion := <-s.motionChannel:
if motion {
out <- nog.Message{What: "motion detected"}
const duration = 60 * time.Second
if motionTimer == nil {
s.Motion = true
motionTimer = time.NewTimer(duration)
motionTimeout = motionTimer.C // enable motionTimeout case
} else {
motionTimer.Reset(duration)
}
}
case <-motionTimeout:
s.Motion = false
motionTimer = nil
motionTimeout = nil
out <- nog.Message{What: "motion detected timeout"}
}
}
done:
out <- nog.Message{What: "stopped"}
close(out)
}
示例15: slowloris
func slowloris(opts options) {
var conn net.Conn
var err error
var timerChan <-chan time.Time
var timer *time.Timer
if opts.finishAfter > 0 {
timer = time.NewTimer(time.Duration(opts.finishAfter) * time.Second)
timerChan = timer.C
}
loop:
for {
if conn != nil {
conn.Close()
}
conn, err = openConnection(opts)
if err != nil {
continue
}
if _, err = fmt.Fprintf(conn, "%s %s HTTP/1.1\r\n", opts.method, opts.resource); err != nil {
continue
}
header := createHeader(opts.target)
if err = header.Write(conn); err != nil {
continue
}
for {
select {
case <-time.After(time.Duration(opts.interval) * time.Second):
if timer != nil {
timer.Reset(time.Duration(opts.finishAfter) * time.Second)
}
if _, err := fmt.Fprintf(conn, "%s\r\n", opts.dosHeader); err != nil {
continue loop
}
// if timerChan is nil (finishAfter =< 0) the case involving it will be omitted
case <-timerChan:
fmt.Fprintf(conn, "\r\n")
ioutil.ReadAll(conn) // omit return values
conn.Close()
continue loop
}
}
}
}