当前位置: 首页>>代码示例>>Golang>>正文


Golang Ticker.Stop方法代码示例

本文整理汇总了Golang中Time.Ticker.Stop方法的典型用法代码示例。如果您正苦于以下问题:Golang Ticker.Stop方法的具体用法?Golang Ticker.Stop怎么用?Golang Ticker.Stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Time.Ticker的用法示例。


在下文中一共展示了Ticker.Stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: watch

func (r *LedReporter) watch() {
	var t *time.Ticker = time.NewTicker(1 * time.Minute)

	for {
		select {
		case color := <-r.blinkChan:
			if t != nil {
				t.Stop()
			}

			led.Off()

			switch color {
			case RED:
				led.Red(true)
			case BLUE:
				led.Blue(true)
			case GREEN:
				led.Green(true)
			}

			t = time.NewTicker(100 * time.Millisecond)
		case <-t.C:
			led.Off()

			if registered {
				led.Blue(true)
			} else {
				led.Off()
			}
		}
	}
}
开发者ID:carriercomm,项目名称:examples-1,代码行数:33,代码来源:service.go

示例2: tickHandler

// Ticker Function
func (c *cclient) tickHandler(ticker *time.Ticker) {
	defer LOGV.Println("client has stopped ticking.")
	for {
		select {
		case <-ticker.C:
			length := len(c.movelist)
			if length > 0 {
				LOGV.Println("movelist is length " + strconv.Itoa(length))
				var translatedMove int
				switch c.movelist[length-1] {
				case lib2048.Up:
					translatedMove = 0
				case lib2048.Right:
					translatedMove = 1
				case lib2048.Down:
					translatedMove = 2
				case lib2048.Left:
					translatedMove = 3
				}
				move := util.ClientMove{translatedMove}
				c.moveQueue <- move
				c.movelist = c.movelist[0:0]
				//				websocket.JSON.Send(c.conn, move)
			}
		case <-c.quitchan:
			ticker.Stop()
			close(c.quitchan)
			return
		}
	}
}
开发者ID:papmech,项目名称:Distributed-2048,代码行数:32,代码来源:cmdlineclient_impl.go

示例3: applyAll

func applyAll(max int, reps []string, apply func(puid string) error) []error {
	ch := make(chan error, len(reps))
	wg := sync.WaitGroup{}
	queue := make(chan struct{}, max) // to avoid hammering TNA
	_, _, tf, _ := config.HarvestOptions()
	var throttle *time.Ticker
	if tf > 0 {
		throttle = time.NewTicker(tf)
		defer throttle.Stop()
	}
	for _, puid := range reps {
		if tf > 0 {
			<-throttle.C
		}
		wg.Add(1)
		go func(puid string) {
			queue <- struct{}{}
			defer wg.Done()
			if err := apply(puid); err != nil {
				ch <- err
			}
			<-queue
		}(puid)
	}
	wg.Wait()
	close(ch)
	var errors []error
	for err := range ch {
		errors = append(errors, err)
	}
	return errors
}
开发者ID:richardlehane,项目名称:siegfried,代码行数:32,代码来源:pronom.go

示例4: RunReader

func (s *Scheme) RunReader(reader factory.Reader) {
	s.closer = reader
	defer s.done.Done()
	s.startReporter()

	buffer := make([]byte, s.bytesPerMessage*2)

	var ticker *time.Ticker
	if s.tickerTime > 0 {
		ticker = time.NewTicker(s.tickerTime)
		defer ticker.Stop()
	}

	for {
		if ticker != nil {
			<-ticker.C
		}

		if s.isClosed() {
			break
		}

		count, err := reader.Read(buffer)
		s.countMessage(count, err)
	}
}
开发者ID:myshkin5,项目名称:netspel,代码行数:26,代码来源:scheme.go

示例5: startPwmLoop

func (p *pin) startPwmLoop(initialValue int) {
	if p.pwmLoop != nil {
		p.pwmLoop <- initialValue
		return
	}
	p.pwmLoop = make(chan int)
	p.quitPwmLoop = make(chan chan error)

	go func() {
		var err error
		var period time.Duration = 20 * time.Millisecond
		var highDuration time.Duration
		var ticker *time.Ticker = time.NewTicker(period)
		defer func() {
			// cleanup
			close(p.pwmLoop)
			close(p.quitPwmLoop)

			p.pwmLoop = nil
			p.quitPwmLoop = nil

			ticker.Stop()
		}()

		for {
			select {
			case v := <-p.pwmLoop:
				switch {
				case v == 0:
					p.SetLow()
					return
				case v == 100:
					p.SetHigh()
					return
				default:
					highDuration = valueToDuration(v, period)
				}
			case reply := <-p.quitPwmLoop:
				reply <- nil
				return
			case <-ticker.C:
				err = p.SetHigh()
				if err != nil {
					reply := <-p.quitPwmLoop
					reply <- err
					return
				}

				time.Sleep(highDuration)

				err = p.SetLow()
				if err != nil {
					reply := <-p.quitPwmLoop
					reply <- err
					return
				}
			}
		}
	}()
}
开发者ID:paulbellamy,项目名称:gpio,代码行数:60,代码来源:gpio.go

示例6: workerProviderRun

func workerProviderRun(w *worker.Worker, args ...interface{}) {
	var (
		prov       = w.Props[0].(*provider.Provider)
		timeTicker *time.Ticker
		timeChan   <-chan time.Time
	)

	defer func() { w.State = worker.JobStopped }()
	defer w.Shutdown()

	logger.Log(logger.LevelDebug, "provider", "%s: starting", prov.Name)

	// If provider `refresh_interval` has been configured, set up a time ticker
	if prov.Config.RefreshInterval > 0 {
		timeTicker = time.NewTicker(time.Duration(prov.Config.RefreshInterval) * time.Second)
		timeChan = timeTicker.C
	}

	for {
		select {
		case _ = <-timeChan:
			logger.Log(logger.LevelDebug, "provider", "%s: performing refresh from connector", prov.Name)

			if err := prov.Connector.Refresh(prov.Name, prov.Filters.Input); err != nil {
				logger.Log(logger.LevelError, "provider", "%s: unable to refresh: %s", prov.Name, err)
				continue
			}

			prov.LastRefresh = time.Now()

		case cmd := <-w.ReceiveJobSignals():
			switch cmd {
			case jobSignalRefresh:
				logger.Log(logger.LevelInfo, "provider", "%s: received refresh command", prov.Name)

				if err := prov.Connector.Refresh(prov.Name, prov.Filters.Input); err != nil {
					logger.Log(logger.LevelError, "provider", "%s: unable to refresh: %s", prov.Name, err)
					continue
				}

				prov.LastRefresh = time.Now()

			case jobSignalShutdown:
				logger.Log(logger.LevelInfo, "provider", "%s: received shutdown command, stopping job", prov.Name)

				w.State = worker.JobStopped

				if timeTicker != nil {
					// Stop refresh time ticker
					timeTicker.Stop()
				}

				return

			default:
				logger.Log(logger.LevelNotice, "provider", "%s: received unknown command, ignoring", prov.Name)
			}
		}
	}
}
开发者ID:carriercomm,项目名称:facette,代码行数:60,代码来源:worker_provider.go

示例7: tokenService

// 负责定时更新本地缓存的 access token.
// 使用这种复杂的实现是减少 time.Now() 的调用, 不然每次都要比较 time.Now().
func (c *Client) tokenService() {
	const defaultTickDuration = time.Minute // 设置 44 秒以上就不会超过限制(2000次/日 的限制)

	// 当前定时器的时间间隔, 正常情况下等于当前的 access token 的过期时间减去 10 秒;
	// 异常情况下就要尝试不断的获取, 时间间隔就是 defaultTickDuration.
	currentTickDuration := defaultTickDuration
	var tk *time.Ticker

NewTickDuration:
	for {
		tk = time.NewTicker(currentTickDuration)
		for {
			select {
			case currentTickDuration = <-c.resetRefreshTickChan: // 在别的地方成功获取了 access token, 重置定时器.
				tk.Stop()
				break NewTickDuration

			case <-tk.C:
				resp, err := c.getNewToken()
				switch {
				case err != nil:
					c.update("", err)
					// 出错则重置到 defaultTickDuration
					if currentTickDuration != defaultTickDuration { // 这个判断的目的是避免重置定时器开销
						tk.Stop()
						currentTickDuration = defaultTickDuration
						break NewTickDuration
					}
				case resp.ExpiresIn > 10: // 正常情况
					c.update(resp.Token, nil)
					// 根据返回的过期时间来重新设置定时器
					// 设置新的 currentTickDuration, 考虑到网络延时, 提前 10 秒过期
					nextTickDuration := time.Duration(resp.ExpiresIn-10) * time.Second
					if currentTickDuration != nextTickDuration { // 这个判断的目的是避免重置定时器开销
						tk.Stop()
						currentTickDuration = nextTickDuration
						break NewTickDuration
					}
				case resp.ExpiresIn > 0: // 正常情况下不会出现
					c.update(resp.Token, nil)
					// 根据返回的过期时间来重新设置定时器
					nextTickDuration := time.Duration(resp.ExpiresIn) * time.Second
					if currentTickDuration != nextTickDuration { // 这个判断的目的是避免重置定时器开销
						tk.Stop()
						currentTickDuration = nextTickDuration
						break NewTickDuration
					}
				default: // resp.ExpiresIn <= 0, 正常情况下不会出现
					c.update("", fmt.Errorf("tokenService: access token 过期时间应该是正整数: %d", resp.ExpiresIn))
					// 出错则重置到 defaultTickDuration
					if currentTickDuration != defaultTickDuration { // 这个判断的目的是避免重置定时器开销
						tk.Stop()
						currentTickDuration = defaultTickDuration
						break NewTickDuration
					}
				}
			}
		}
	}
}
开发者ID:neatstudio,项目名称:wechat,代码行数:62,代码来源:client_token.go

示例8: StartVerifier

func (s *Server) StartVerifier(ticker *time.Ticker) {
	var err error
	defer DeleteServer(s.LobbyId)

	_, err = s.rcon.Query("status")
	if err != nil {
		err = s.rcon.Reconnect(5 * time.Minute)

		if err != nil {
			publishEvent(Event{
				Name:    DisconnectedFromServer,
				LobbyID: s.LobbyId})
			return
		}
	}

	for {
		select {
		case <-ticker.C:
			if !s.Verify() {
				ticker.Stop()
				s.rcon.Close()
				return
			}
		case <-s.StopVerifier:
			helpers.Logger.Debugf("Stopping logger for lobby %d", s.LobbyId)
			s.rcon.Say("[tf2stadium.com] Lobby Ended.")
			s.rcon.RemoveTag("TF2Stadium")
			ticker.Stop()
			s.rcon.Close()
			return
		}
	}
}
开发者ID:TF2Stadium,项目名称:Pauling,代码行数:34,代码来源:server.go

示例9: lookupdLoop

// poll all known lookup servers every LookupdPollInterval
func (r *Consumer) lookupdLoop() {
	// add some jitter so that multiple consumers discovering the same topic,
	// when restarted at the same time, dont all connect at once.
	jitter := time.Duration(int64(r.rng.Float64() *
		r.config.LookupdPollJitter * float64(r.config.LookupdPollInterval)))
	var ticker *time.Ticker

	select {
	case <-time.After(jitter):
	case <-r.exitChan:
		goto exit
	}

	ticker = time.NewTicker(r.config.LookupdPollInterval)

	for {
		select {
		case <-ticker.C:
			r.queryLookupd()
		case <-r.lookupdRecheckChan:
			r.queryLookupd()
		case <-r.exitChan:
			goto exit
		}
	}

exit:
	if ticker != nil {
		ticker.Stop()
	}
	r.log(LogLevelInfo, "exiting lookupdLoop")
	r.wg.Done()
}
开发者ID:pgpst,项目名称:pgpst,代码行数:34,代码来源:consumer.go

示例10: Run

// Run is roleManager's main loop.
func (rm *roleManager) Run() {
	defer close(rm.doneChan)

	var (
		nodes    []*api.Node
		ticker   *time.Ticker
		tickerCh <-chan time.Time
	)

	watcher, cancelWatch, err := store.ViewAndWatch(rm.store,
		func(readTx store.ReadTx) error {
			var err error
			nodes, err = store.FindNodes(readTx, store.All)
			return err
		},
		state.EventUpdateNode{})
	defer cancelWatch()

	if err != nil {
		log.L.WithError(err).Error("failed to check nodes for role changes")
	} else {
		for _, node := range nodes {
			rm.pending[node.ID] = node
			rm.reconcileRole(node)
		}
		if len(rm.pending) != 0 {
			ticker = time.NewTicker(roleReconcileInterval)
			tickerCh = ticker.C
		}
	}

	for {
		select {
		case event := <-watcher:
			node := event.(state.EventUpdateNode).Node
			rm.pending[node.ID] = node
			rm.reconcileRole(node)
			if len(rm.pending) != 0 && ticker == nil {
				ticker = time.NewTicker(roleReconcileInterval)
				tickerCh = ticker.C
			}
		case <-tickerCh:
			for _, node := range rm.pending {
				rm.reconcileRole(node)
			}
			if len(rm.pending) == 0 {
				ticker.Stop()
				ticker = nil
				tickerCh = nil
			}
		case <-rm.ctx.Done():
			if ticker != nil {
				ticker.Stop()
			}
			return
		}
	}
}
开发者ID:docker,项目名称:docker,代码行数:59,代码来源:role_manager.go

示例11: messageAggregator

// one per broker
// groups messages together into appropriately-sized batches for sending to the broker
// based on https://godoc.org/github.com/eapache/channels#BatchingChannel
func (p *Producer) messageAggregator(broker *Broker, input chan *ProducerMessage) {
	var ticker *time.Ticker
	var timer <-chan time.Time
	if p.config.FlushFrequency > 0 {
		ticker = time.NewTicker(p.config.FlushFrequency)
		timer = ticker.C
	}

	var buffer []*ProducerMessage
	var doFlush chan []*ProducerMessage
	var bytesAccumulated int

	flusher := make(chan []*ProducerMessage)
	go withRecover(func() { p.flusher(broker, flusher) })

	for {
		select {
		case msg := <-input:
			if msg == nil {
				goto shutdown
			}

			if (bytesAccumulated+msg.byteSize() >= forceFlushThreshold()) ||
				(p.config.Compression != CompressionNone && bytesAccumulated+msg.byteSize() >= p.config.MaxMessageBytes) ||
				(p.config.MaxMessagesPerReq > 0 && len(buffer) >= p.config.MaxMessagesPerReq) {
				Logger.Println("producer/aggregator maximum request accumulated, forcing blocking flush")
				flusher <- buffer
				buffer = nil
				doFlush = nil
				bytesAccumulated = 0
			}

			buffer = append(buffer, msg)
			bytesAccumulated += msg.byteSize()

			if len(buffer) >= p.config.FlushMsgCount ||
				(p.config.FlushByteCount > 0 && bytesAccumulated >= p.config.FlushByteCount) {
				doFlush = flusher
			}
		case <-timer:
			doFlush = flusher
		case doFlush <- buffer:
			buffer = nil
			doFlush = nil
			bytesAccumulated = 0
		}
	}

shutdown:
	if ticker != nil {
		ticker.Stop()
	}
	if len(buffer) > 0 {
		flusher <- buffer
	}
	close(flusher)
}
开发者ID:pkoro,项目名称:go-kafka,代码行数:60,代码来源:producer.go

示例12: loop

func (x *Sieve) loop() {
	// Close out connection
	defer func() {
		close(x.k)
		x.Mute()
		x.dual.Mute()
	}()
	// Timeout ticker
	var tkr *time.Ticker
	var expchan <-chan time.Time
	if x.exp > 0 {
		tkr = time.NewTicker(x.exp)
		expchan = tkr.C
	}
	defer func() {
		if tkr != nil {
			tkr.Stop()
		}
	}()
	// Main loop
	var nrecv, nticks int
	for {
		select {
		case <-x.abrt:
			x.Frame.Println("Aborting sieve.")
			return
		case <-expchan:
			nticks++
			if nticks > 1 {
				x.Frame.Println("Breaking connection due to timeout.")
				return // Timeout with nothing send kills the connection
			}
		case q, ok := <-x.s:
			nticks = 0
			if !ok {
				return // s-channel closed, i.e. a Close on the sending HalfConn, kills the connection
			}
			nrecv++
			send := nrecv <= x.nok
			forceEOF := nrecv+1 > x.nok+x.ndrop
			if send {
				if _, ok := q.(eof); ok {
					x.Frame.Println("SIEVE ---> EOF") // ??
				}
				x.t.Send(q)
			}
			// OK tells conn.Write whether the message was delivered
			// EOF tells conn.Write whether the connection has ended after the write
			x.k <- feedback{OK: send, EOF: forceEOF}
			if forceEOF {
				x.Mute()
				x.dual.Mute()
			}
			//x.Printf("X=%-2d dlvr=%4v forceEOF=%4v (%d,%d)", nrecv, send, forceEOF, x.nok, x.ndrop)
		}
	}
}
开发者ID:prodigeni,项目名称:circuit,代码行数:57,代码来源:middle.go

示例13: main

func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		go func() {
			time.Sleep(10 * time.Second)
			pprof.StopCPUProfile()
		}()
	}

	app.Main(func(a app.App) {
		var logdbg *time.Ticker
		var glctx gl.Context
		for ev := range a.Events() {
			switch ev := a.Filter(ev).(type) {
			case lifecycle.Event:
				switch ev.Crosses(lifecycle.StageVisible) {
				case lifecycle.CrossOn:
					logdbg = time.NewTicker(time.Second)
					go func() {
						for range logdbg.C {
							log.Printf("fps=%-4v underruns=%-4v buflen=%-4v tickavg=%-12s drift=%s\n",
								fps, al.Underruns(), al.BufLen(), al.TickAverge(), al.DriftApprox())
						}
					}()
					glctx = ev.DrawContext.(gl.Context)
					onStart(glctx)
					al.Start()
				case lifecycle.CrossOff:
					glctx = nil
					logdbg.Stop()
					al.Stop()
					al.CloseDevice()
				}
			case touch.Event:
				env.Touch(ev)
			case size.Event:
				if glctx == nil {
					a.Send(ev)
				} else {
					onLayout(ev)
				}
			case paint.Event:
				if glctx != nil {
					onPaint(glctx)
					a.Publish()
					a.Send(paint.Event{})
				}
			}
		}
	})
}
开发者ID:dskinner,项目名称:snd,代码行数:56,代码来源:main.go

示例14: clicker

// clicker handles possibly multiple click mouse actions.
// It should be called with the first mouse event that triggered
// the action (which should have m.Buttons != 0), and the
// channel from which it will read mouse events.
// It sends a mouse event on c for each click;
// and closes c when no more clicks are available.
// If the last event has Buttons == 0, the mouse
// has been released, otherwise the user continues
// to drag the mouse. Only the last event may have Buttons==0.
//
func clicker(m0 draw.Mouse, mc <-chan draw.Mouse) (clicks, final <-chan draw.Mouse) {
	var t *time.Ticker
	c := make(chan draw.Mouse)
	fc := make(chan draw.Mouse, 1)
	go func() {
		c <- m0
		m := m0
	tracking:
		for !closed(mc) {
			// wait for button up or delta or time to move outside limit.
			for m = range mc {
				if m.Buttons == 0 {
					// does a long click with no intervening movement still count as a click?
					break
				}
				d := m.Sub(m0.Point)
				if m.Nsec-m0.Nsec > ClickTime || d.X*d.X+d.Y*d.Y > ClickDist {
					break tracking
				}
			}

			t = time.NewTicker(ClickTime)
			// wait for button down or delta or time to move outside limit.
		buttonDown:
			for {
				select {
				case m = <-mc:
					if closed(mc) {
						break tracking
					}
					d := m.Sub(m0.Point)
					if m.Nsec-m0.Nsec > ClickTime || d.X*d.X+d.Y*d.Y > ClickDist {
						break tracking
					}
					if m.Buttons != 0 {
						break buttonDown
					}
				case <-t.C:
					break tracking
				}
			}
			t.Stop()
			t = nil
			c <- m0
			m0 = m
		}
		if t != nil {
			t.Stop()
		}
		close(c)
		fc <- m
		return
	}()
	return c, fc
}
开发者ID:zenoss,项目名称:rog-go,代码行数:65,代码来源:mandel.go

示例15: keepalive

func keepalive(conn ssh.Conn, ticker *time.Ticker, stopCh chan struct{}) {
	for {
		select {
		case <-ticker.C:
			_, _, _ = conn.SendRequest("[email protected]", true, nil)
		case <-stopCh:
			ticker.Stop()
			return
		}
	}
}
开发者ID:Reejoshi,项目名称:cli,代码行数:11,代码来源:ssh.go


注:本文中的Time.Ticker.Stop方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。