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


Golang Time.NewTicker函数代码示例

本文整理汇总了Golang中Time.NewTicker函数的典型用法代码示例。如果您正苦于以下问题:Golang NewTicker函数的具体用法?Golang NewTicker怎么用?Golang NewTicker使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewTicker函数的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: RunLift

//Called by main
//Initializes all the other modules and goes to eternal for loop
func RunLift(quitCh chan bool) {
	var buttonPress = make(chan driver.Button, 5)
	var status = make(chan driver.LiftStatus, 5)
	myID = udp.NetInit(toNetwork, fromNetwork, quitCh)
	fsmelev.Init(floorOrder, setLight, status, buttonPress, motorStopCh, quitCh)
	restoreBackup()
	liftStatus = <-status
	ticker1 := time.NewTicker(10 * time.Millisecond).C
	ticker2 := time.NewTicker(5 * time.Millisecond).C
	log.Println("Network UP \n Driver UP \n My id:", myID)
	for {
		select {
		case button = <-buttonPress:
			newKeyPress(button)
		case liftStatus = <-status:
			runQueue(liftStatus, floorOrder)
		case message = <-fromNetwork:
			newMessage(message)
			orderLight(message)
		case <-ticker1:
			checkTimeout()
		case <-ticker2:
			runQueue(liftStatus, floorOrder)
		case <-quitCh:
			return
		}
	}
}
开发者ID:lauritsriple,项目名称:TTK4145-Sanntid,代码行数:30,代码来源:control.go

示例3: newMqttEngine

func newMqttEngine() (*mqttEngine, error) {

	murl, err := url.Parse(*mqttURL)

	if err != nil {
		return nil, err
	}

	mq := &mqttEngine{}

	// Create an MQTT Client.
	cli := client.New(&client.Options{
		ErrorHandler: mq.handleClientError,
	})

	mq.murl = murl
	mq.cli = cli

	mq.attemptConnect()

	//mq.publisher = publisher
	mq.pollTicker = time.NewTicker(time.Second * 1)
	mq.pubTicker = time.NewTicker(time.Second * 15)

	go poll(mq)
	go publish(mq, "Ready to publish")

	return mq, nil
}
开发者ID:paulcull,项目名称:mqtt-webbrick,代码行数:29,代码来源:mqttEngine.go

示例4: NewHTTPFrontend

// create a new http based frontend
func NewHTTPFrontend(daemon *NNTPDaemon, config map[string]string, url string) Frontend {
	var front httpFrontend
	front.daemon = daemon
	front.regenBoardTicker = time.NewTicker(time.Second * 10)
	front.ukkoTicker = time.NewTicker(time.Second * 30)
	front.regenBoard = make(map[string]groupRegenRequest)
	front.attachments = mapGetInt(config, "allow_files", 1) == 1
	front.bindaddr = config["bind"]
	front.name = config["name"]
	front.webroot_dir = config["webroot"]
	front.static_dir = config["static_files"]
	front.template_dir = config["templates"]
	front.prefix = config["prefix"]
	front.regen_on_start = config["regen_on_start"] == "1"
	front.regen_threads = mapGetInt(config, "regen_threads", 1)
	front.store = sessions.NewCookieStore([]byte(config["api-secret"]))
	front.store.Options = &sessions.Options{
		// TODO: detect http:// etc in prefix
		Path:   front.prefix,
		MaxAge: 600,
	}
	front.postchan = make(chan NNTPMessage, 16)
	front.recvpostchan = make(chan NNTPMessage, 16)
	front.regenThreadChan = make(chan ArticleEntry, 16)
	front.regenGroupChan = make(chan groupRegenRequest, 8)
	return front
}
开发者ID:kurtcoke,项目名称:srndv2,代码行数:28,代码来源:frontend_http.go

示例5: TestCounterRate

// BUG: This test will most likely fail on a highly loaded
// system
func TestCounterRate(t *testing.T) {
	c := NewCounter()
	// increment counter every 10ms in two goroutines
	// rate ~ 200/sec
	tick1 := time.NewTicker(time.Millisecond * 10)
	go func() {
		for _ = range tick1.C {
			c.Add(1)
		}
	}()
	tick2 := time.NewTicker(time.Millisecond * 10)
	go func() {
		for _ = range tick2.C {
			c.Add(1)
		}
	}()

	time.Sleep(time.Millisecond * 5000)
	tick1.Stop()
	tick2.Stop()

	want := 200.0
	out := c.ComputeRate()

	if math.Abs(want-out) > 1 {
		t.Errorf("c.ComputeRate() = %v, want %v", out, want)
	}
}
开发者ID:BrianIp,项目名称:prodeng,代码行数:30,代码来源:metrics_test.go

示例6: manage

// manage manages outgoing clients. Periodically, the infostore is
// scanned for infos with hop count exceeding the MaxHops
// threshold. If the number of outgoing clients doesn't exceed
// maxPeers(), a new gossip client is connected to a randomly selected
// peer beyond MaxHops threshold. Otherwise, the least useful peer
// node is cut off to make room for a replacement. Disconnected
// clients are processed via the disconnected channel and taken out of
// the outgoing address set. If there are no longer any outgoing
// connections or the sentinel gossip is unavailable, the bootstrapper
// is notified via the stalled conditional variable.
func (g *Gossip) manage() {
	stopper := g.server.stopper

	stopper.RunWorker(func() {
		cullTicker := time.NewTicker(g.jitteredInterval(g.cullInterval))
		stallTicker := time.NewTicker(g.jitteredInterval(g.stallInterval))
		defer cullTicker.Stop()
		defer stallTicker.Stop()
		for {
			select {
			case <-stopper.ShouldStop():
				return
			case c := <-g.disconnected:
				g.doDisconnected(stopper, c)
			case nodeID := <-g.tighten:
				g.tightenNetwork(stopper, nodeID)
			case <-cullTicker.C:
				g.cullNetwork()
			case <-stallTicker.C:
				g.mu.Lock()
				g.maybeSignalStalledLocked()
				g.mu.Unlock()
			}
		}
	})
}
开发者ID:binlijin,项目名称:cockroach,代码行数:36,代码来源:gossip.go

示例7: Run

func (r *report) Run(shutdown <-chan bool, wg *sync.WaitGroup) {
	defer wg.Done()
	ticker := time.NewTicker(time.Second)
	ticker30 := time.NewTicker(30 * time.Second)
	defer ticker.Stop()

	r.printColumns()
	for {
		select {
		case <-shutdown:
			r.printStatusCodes()
			r.printHistogram()
			r.printLatencies()
			if r.total.errorCount.Val() > 0 {
				r.printErrors()
			}
			return
		case <-ticker.C:
			r.printStat(r.second)
			r.clear(r.second)

		case <-ticker30.C:
			r.printStat(r.half)
			r.clear(r.half)
			r.printColumns()
		}
	}
}
开发者ID:heshed,项目名称:boom,代码行数:28,代码来源:print.go

示例8: initializeTickers

func (e *Engine) initializeTickers() {
	freq := computeSpawnFrequency(e.Scenario.test_duration.Seconds(),
		float64(e.Scenario.total_users))
	e.spawn_ticker = time.NewTicker(freq)
	e.test_progress_ticker = time.NewTicker(e.progress_update_frequency)
	e.test_completed_ticker = time.NewTicker(e.Scenario.test_duration)
}
开发者ID:vgheri,项目名称:GoSmashIt,代码行数:7,代码来源:engine.go

示例9: pingLoop

//Pings the server if we have not recived any messages for 5 minutes
func (irc *Connection) pingLoop() {
	ticker := time.NewTicker(1 * time.Minute)   //Tick every minute.
	ticker2 := time.NewTicker(15 * time.Minute) //Tick every 15 minutes.
	for {
		select {
		case <-ticker.C:
			//Ping if we haven't received anything from the server within 4 minutes
			irc.lastMessageMutex.Lock()
			if time.Since(irc.lastMessage) >= (4 * time.Minute) {
				irc.SendRawf("PING %d", time.Now().UnixNano())
			}
			irc.lastMessageMutex.Unlock()
		case <-ticker2.C:
			//Ping every 15 minutes.
			irc.SendRawf("PING %d", time.Now().UnixNano())
			//Try to recapture nickname if it's not as configured.
			if irc.nick != irc.nickcurrent {
				irc.nickcurrent = irc.nick
				irc.SendRawf("NICK %s", irc.nick)
			}
		case <-irc.endping:
			ticker.Stop()
			ticker2.Stop()
			irc.pingerExit <- true
			return
		}
	}
}
开发者ID:jpoz,项目名称:go-ircevent,代码行数:29,代码来源:irc.go

示例10: startGossip

// startGossip loops on a periodic ticker to gossip node-related
// information. Starts a goroutine to loop until the node is closed.
func (n *Node) startGossip(ctx context.Context, stopper *stop.Stopper) {
	stopper.RunWorker(func() {
		gossipStoresInterval := envutil.EnvOrDefaultDuration("gossip_stores_interval",
			gossip.DefaultGossipStoresInterval)
		statusTicker := time.NewTicker(gossipStatusInterval)
		storesTicker := time.NewTicker(gossipStoresInterval)
		nodeTicker := time.NewTicker(gossipNodeDescriptorInterval)
		defer storesTicker.Stop()
		defer nodeTicker.Stop()
		n.gossipStores(ctx) // one-off run before going to sleep
		for {
			select {
			case <-statusTicker.C:
				n.ctx.Gossip.LogStatus()
			case <-storesTicker.C:
				n.gossipStores(ctx)
			case <-nodeTicker.C:
				if err := n.ctx.Gossip.SetNodeDescriptor(&n.Descriptor); err != nil {
					log.Warningf(ctx, "couldn't gossip descriptor for node %d: %s", n.Descriptor.NodeID, err)
				}
			case <-stopper.ShouldStop():
				return
			}
		}
	})
}
开发者ID:yangxuanjia,项目名称:cockroach,代码行数:28,代码来源:node.go

示例11: VersionsSyncJob

func VersionsSyncJob() {
	versionWait.Add(1)
	defer versionWait.Done()
	QueryDeployVersions()
	tickCheck := time.NewTicker(10 * 1000 * time.Millisecond)
	defer tickCheck.Stop()
	tickDownload := time.NewTicker(1000 * time.Millisecond)

	for {
		select {
		case <-quitSync:
			tickDownload.Stop()
			return
		case <-tickCheck.C:
			QueryDeployVersions()
		case <-tickDownload.C:
			d := needDownload
			DownloadDeployVersions()
			if d != needDownload {
				tickDownload.Stop()
				if needDownload {
					tickDownload = time.NewTicker(10 * time.Millisecond)
				} else {
					tickDownload = time.NewTicker(1000 * time.Millisecond)
				}
			}
		}
	}
}
开发者ID:ChristophPech,项目名称:servertest,代码行数:29,代码来源:versions.go

示例12: RunScraper

// RunScraper implements Target.
func (t *Target) RunScraper(sampleAppender storage.SampleAppender) {
	defer close(t.scraperStopped)

	lastScrapeInterval := t.interval()

	log.Debugf("Starting scraper for target %v...", t)

	select {
	case <-time.After(t.offset(lastScrapeInterval)):
		// Continue after scraping offset.
	case <-t.scraperStopping:
		return
	}

	ticker := time.NewTicker(lastScrapeInterval)
	defer ticker.Stop()

	t.scrape(sampleAppender)

	// Explanation of the contraption below:
	//
	// In case t.scraperStopping has something to receive, we want to read
	// from that channel rather than starting a new scrape (which might take very
	// long). That's why the outer select has no ticker.C. Should t.scraperStopping
	// not have anything to receive, we go into the inner select, where ticker.C
	// is in the mix.
	for {
		select {
		case <-t.scraperStopping:
			return
		default:
			select {
			case <-t.scraperStopping:
				return
			case <-ticker.C:
				took := time.Since(t.status.LastScrape())

				intervalStr := lastScrapeInterval.String()

				// On changed scrape interval the new interval becomes effective
				// after the next scrape.
				if iv := t.interval(); iv != lastScrapeInterval {
					ticker.Stop()
					ticker = time.NewTicker(iv)
					lastScrapeInterval = iv
				}

				targetIntervalLength.WithLabelValues(intervalStr).Observe(
					float64(took) / float64(time.Second), // Sub-second precision.
				)
				if sampleAppender.NeedsThrottling() {
					targetSkippedScrapes.WithLabelValues(intervalStr).Inc()
					t.status.setLastError(errSkippedScrape)
					continue
				}
				t.scrape(sampleAppender)
			}
		}
	}
}
开发者ID:izogain,项目名称:prometheus,代码行数:61,代码来源:target.go

示例13: GetAllNetDevice

//获取所有网络设备信息
func (this *db) GetAllNetDevice() ([]*NetDevice, error) {
	rows, err := this.Conn.Query("select d.id, d.uuid, d.ip, d.snmp_version, d.snmp_community, d.snmp_port," +
		"d.config_update_interval, d.check_interval, p.ip from network_device as d left join system_proxy as p on d.proxy_id = p.id")
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	devices := []*NetDevice{}
	for rows.Next() {
		device := &NetDevice{}
		var proxy sql.NullString
		if err := rows.Scan(&device.ID, &device.UUID, &device.IpAddr, &device.SnmpVersion,
			&device.SnmpCommunity, &device.SnmpPort, &device.UpdateInterval,
			&device.CheckInterval, &proxy); err != nil {
			continue
		}
		device.Proxy = proxy.String
		device.stopChan = make(chan struct{})
		device.updateTicker = time.NewTicker(time.Second * time.Duration(device.UpdateInterval))
		device.checkTicker = time.NewTicker(time.Second * time.Duration(device.CheckInterval))
		device.DeviceInterfaces = make(map[string]*DeviceInterface)
		//获取oid
		if oids, err := this.GetCustomOidByDeviceID(device.ID); err == nil {
			device.CustomOids = oids
		}
		//获取端口
		ifts := this.GetInterfacesByDeviceId(device.ID)
		for _, ift := range ifts {
			device.DeviceInterfaces[string(ift.Index)] = ift
		}
		devices = append(devices, device)
	}
	return devices, nil
}
开发者ID:y8y,项目名称:OWL-v3,代码行数:35,代码来源:mysql.go

示例14: countDown

func countDown() {
	endTimer := time.NewTimer(time.Duration(state.TimeLeft) * time.Millisecond)
	gameTicker := time.NewTicker(1 * time.Millisecond)
	paused := false

	for {
		select {
		case <-gameTicker.C:
			state.TimeLeft--

		case shouldPause := <-pauseChannel:
			if shouldPause && !paused {
				endTimer.Stop()
				gameTicker.Stop()
				paused = true
			} else if !shouldPause && paused {
				endTimer.Reset(time.Duration(state.TimeLeft) * time.Millisecond)
				gameTicker = time.NewTicker(1 * time.Millisecond)
				paused = false
			}

		case <-interruptChannel:
			endTimer.Stop()
			gameTicker.Stop()

		case <-endTimer.C:
			endTimer.Stop()
			gameTicker.Stop()
			go intermission()
			return
		}
	}
}
开发者ID:hycxa,项目名称:waiter,代码行数:33,代码来源:game_timing.go

示例15: pingLoop

// Pings the server if we have not received any messages for 5 minutes
// to keep the connection alive. To be used as a goroutine.
func (irc *Connection) pingLoop() {
	defer irc.Done()
	ticker := time.NewTicker(1 * time.Minute) // Tick every minute for monitoring
	ticker2 := time.NewTicker(irc.PingFreq)   // Tick at the ping frequency.
	for {
		select {
		case <-ticker.C:
			//Ping if we haven't received anything from the server within the keep alive period
			if time.Since(irc.lastMessage) >= irc.KeepAlive {
				irc.SendRawf("PING %d", time.Now().UnixNano())
			}
		case <-ticker2.C:
			//Ping at the ping frequency
			irc.SendRawf("PING %d", time.Now().UnixNano())
			//Try to recapture nickname if it's not as configured.
			if irc.nick != irc.nickcurrent {
				irc.nickcurrent = irc.nick
				irc.SendRawf("NICK %s", irc.nick)
			}
		case <-irc.end:
			ticker.Stop()
			ticker2.Stop()
			return
		}
	}
}
开发者ID:Elemental-IRCd,项目名称:irc,代码行数:28,代码来源:irc.go


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