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


Golang Time.Tick函数代码示例

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


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

示例1: Watcher

// Runs in its own goroutine, listens for interval tickers which trigger it to
// a) try to open any upopened files and b) read any new data from already
// opened files.
func (fm *FileMonitor) Watcher() {
	discovery := time.Tick(fm.discoverInterval)
	checkStat := time.Tick(fm.statInterval)

	ok := true

	for ok {
		select {
		case _, ok = <-fm.stopChan:
			break
		case <-checkStat:
			for fileName, _ := range fm.fds {
				ok = fm.ReadLines(fileName)
				if !ok {
					break
				}
			}
		case <-discovery:
			// Check to see if the files exist now, start reading them
			// if we can, and watch them
			for fileName, _ := range fm.discover {
				if fm.OpenFile(fileName) == nil {
					delete(fm.discover, fileName)
				}
			}
		}
	}
	for _, fd := range fm.fds {
		fd.Close()
	}
}
开发者ID:pjzjchn,项目名称:heka,代码行数:34,代码来源:logfile_input.go

示例2: Execute

func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
	const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
	changes <- svc.Status{State: svc.StartPending}
	fasttick := time.Tick(500 * time.Millisecond)
	slowtick := time.Tick(2 * time.Second)
	tick := fasttick
	changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
loop:
	for {
		select {
		case <-tick:
			beep()
		case c := <-r:
			switch c.Cmd {
			case svc.Interrogate:
				changes <- c.CurrentStatus
				// testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4
				time.Sleep(100 * time.Millisecond)
				changes <- c.CurrentStatus
			case svc.Stop, svc.Shutdown:
				break loop
			case svc.Pause:
				changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted}
				tick = slowtick
			case svc.Continue:
				changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
				tick = fasttick
			default:
				elog.Error(1, fmt.Sprintf("unexpected control request #%d", c))
			}
		}
	}
	changes <- svc.Status{State: svc.StopPending}
	return
}
开发者ID:winlabs,项目名称:winsvc,代码行数:35,代码来源:service.go

示例3: startAccelometer

func (m *manager) startAccelometer(app sender, d time.Duration) {
	go func() {
		ev := make([]C.float, 4)
		var lastTimestamp int64
		for {
			select {
			case <-doneA:
				return
			default:
				C.GoIOS_readAccelerometer(m.m, (*C.float)(unsafe.Pointer(&ev[0])))
				t := int64(ev[0] * 1000 * 1000)
				if t > lastTimestamp {
					// TODO(jbd): Do we need to convert the values to another unit?
					// How does iOS units compate to the Android units.
					app.Send(Event{
						Sensor:    Accelerometer,
						Timestamp: t,
						Data:      []float64{float64(ev[1]), float64(ev[2]), float64(ev[3])},
					})
					lastTimestamp = t
					<-time.Tick(d)
				} else {
					<-time.Tick(d / 2)
				}
			}
		}
	}()
}
开发者ID:rakyll,项目名称:experimental,代码行数:28,代码来源:darwin_armx.go

示例4: run

func (r *reporter) run() {
	intervalTicker := time.Tick(r.interval)
	//pingTicker := time.Tick(time.Second * 5)
	pingTicker := time.Tick(r.interval / 2)

	for {
		select {
		// TODO on shutdown, flush all metrics

		case <-r.stop:
			return

		case <-intervalTicker:
			if err := r.send(); err != nil {
				log.Error("unable to send metrics to InfluxDB. err=%v", err)
			}

		case <-pingTicker:
			_, _, err := r.client.Ping()
			if err != nil {
				log.Error("got error while sending a ping to InfluxDB, trying to recreate client. err=%v", err)

				if err = r.makeClient(); err != nil {
					log.Error("unable to make InfluxDB client. err=%v", err)
				}
			}
		}
	}
}
开发者ID:chendx79,项目名称:gafka,代码行数:29,代码来源:influxdb.go

示例5: run

func (game *Game) run() {
	timeInterval := 2e8
	updateTicker := time.Tick(30e9)
	moveTicker := time.Tick(time.Duration(timeInterval))
	foodTicker := time.Tick(1e9)
	for {
		select {
		case <-updateTicker:
			timeInterval /= 2
			moveTicker = time.Tick(time.Duration(timeInterval))
		case <-moveTicker:
			game.PlayerOne.AdvancePosition()
			game.PlayerTwo.AdvancePosition()
			game.checkForLoser()
			game.PlayerOne.ToClient <- game
			game.PlayerTwo.ToClient <- game
			if game.HasEnded {
				close(game.PlayerOne.ToClient)
				close(game.PlayerTwo.ToClient)
				return
			} else {
				game.eatFood()
			}
		case <-foodTicker:
			x := rand.Int() % game.Width
			y := rand.Int() % game.Height
			game.Food = append(game.Food, [2]int{x, y})
		case update := <-game.PlayerOne.FromClient:
			game.PlayerOne.UpdateHeading(update)
		case update := <-game.PlayerTwo.FromClient:
			game.PlayerTwo.UpdateHeading(update)
		}
	}
}
开发者ID:grncdr,项目名称:hipstersnake,代码行数:34,代码来源:game.go

示例6: rate_limiting

func rate_limiting() {
	fmt.Println("<rate_limiting>")
	fmt.Println("<------------->")

	// First we'll look at basic rate limiting. Suppose
	// we want to limit our handling of incoming requests.
	// We'll serve these requests off a channel of the
	// same name.
	requests := make(chan int, 5)
	for i := 1; i <= 5; i++ {
		requests <- i
	}
	close(requests)

	// This `limiter` channel will receive a value
	// every 200 milliseconds. This is the regulator in
	// our rate limiting scheme.
	limiter := time.Tick(time.Millisecond * 200)

	// By blocking on a receive from the `limiter` channel
	// before serving each request, we limit ourselves to
	// 1 request every 200 milliseconds.
	for req := range requests {
		<-limiter
		fmt.Println("request", req, time.Now())
	}

	// We may want to allow short bursts of requests in
	// our rate limiting scheme while preserving the
	// overall rate limit. We can accomplish this by
	// buffering our limiter channel. This `burstyLimiter`
	// channel will allow bursts of up to 3 events.
	burstyLimiter := make(chan time.Time, 3)

	// Fill up the channel to represent allowed bursting.
	for i := 0; i < 3; i++ {
		burstyLimiter <- time.Now()
	}

	// Every 200 milliseconds we'll try to add a new
	// value to `burstyLimiter`, up to its limit of 3.
	go func() {
		for t := range time.Tick(time.Millisecond * 200) {
			burstyLimiter <- t
		}
	}()

	// Now simulate 5 more incoming requests. The first
	// 3 of these will benefit from the burst capability
	// of `burstyLimiter`.
	burstyRequests := make(chan int, 5)
	for i := 1; i <= 5; i++ {
		burstyRequests <- i
	}
	close(burstyRequests)
	for req := range burstyRequests {
		<-burstyLimiter
		fmt.Println("request", req, time.Now())
	}
}
开发者ID:klashxx,项目名称:go_by_example,代码行数:60,代码来源:rate_limiting.go

示例7: Loop

func (w *World) Loop() {
	timer1secCh := time.Tick(1 * time.Second)
	fps := 60
	timer60Ch := time.Tick(time.Duration(1000/fps) * time.Millisecond)
loop:
	for {
		select {
		case cmd := <-w.cmdCh:
			//log.Println(cmd)
			switch cmd.Cmd {
			default:
				log.Printf("unknown cmd %v", cmd)
			case "quit":
				break loop
			}
		case ftime := <-timer60Ch:
			ok := w.Do1Frame(ftime)
			if !ok {
				break loop
			}
		case <-timer1secCh:
			log.Printf("%v %v", w, <-go4game.IdGenCh)

			log.Printf("%v", w.octree)
			ol := w.ListNearObj(SnakeDefault.WorldCube)
			for _, o := range ol {
				log.Printf("%v", o)
			}
		}
	}
}
开发者ID:kasworld,项目名称:go4game,代码行数:31,代码来源:world.go

示例8: Lock

// Lock attempts to acquire mutex m. If the lock is already in use, the calling
// goroutine blocks until the mutex is available
func (m *Mutex) Lock() error {
	l, err := m.tryLock()
	if l || err != nil {
		return err
	}
	// if RetryTime is not a positive value, we don't want to retry. Just fail instead.
	if m.RetryTime <= 0 {
		return fmt.Errorf("failed to acquire lock '%s'", m.LockName)
	}
	retryTicker := time.Tick(m.RetryTime)
	var timeoutTicker <-chan time.Time
	if m.Timeout > 0 {
		timeoutTicker = time.Tick(m.Timeout)
	} else {
		// if m.Timeout isn't a positive value, just make an unconnected channel to poll
		// (effectively making the timeout infinite)
		timeoutTicker = make(chan time.Time)
	}
	for {
		select {
		case <-retryTicker:
			l, err := m.tryLock()
			if l || err != nil {
				return err
			}
		case <-timeoutTicker:
			return fmt.Errorf("mutex lock hit timeout of %v", m.Timeout)
		}
	}
}
开发者ID:SmartThingsOSS,项目名称:stcql,代码行数:32,代码来源:mutex.go

示例9: main

func main() {
	start := time.Now()
	counter := 0
	tick := time.Tick(100 * time.Millisecond)
	tick2 := time.Tick(5 * time.Second)
	tick3 := time.Tick(10 * time.Second)
	timeout := time.After(time.Second * 30)

	fmt.Println("Started at ", start)
	for {
		select {
		case <-tick:
			fmt.Print(".")
			counter += 1

		case <-tick2:
			fmt.Println("")
			fmt.Println("Time elapsed: ", time.Since(start))

		case <-tick3:
			fmt.Println("\nCounter:", counter)

		case <-timeout:
			fmt.Println("Timeout")
			os.Exit(0)
		}
	}

}
开发者ID:raittes,项目名称:go-examples,代码行数:29,代码来源:timer.go

示例10: main

func main() {
	lastSeenMessage := time.Now()

	checker := time.Tick(1 * time.Second)
	producer := time.Tick(10 * time.Second)

	log.Println("Started")

	go func() {
		for _ = range producer {
			lastSeenMessage = time.Now()
			log.Println(lastSeenMessage)
		}
	}()

	for _ = range checker {
		checkTime := 5 * time.Second
		lastSeenMessageTime := lastSeenMessage.Add(checkTime).Unix()
		currentTime := time.Now().Unix()

		check := lastSeenMessageTime < currentTime

		log.Println(currentTime, lastSeenMessageTime, check)

		if check {
			panic(fmt.Sprintf("no message received in last %v", checkTime))
		}
	}
}
开发者ID:sent-hil,项目名称:learn,代码行数:29,代码来源:timeout.go

示例11: Watcher

func (fm *FileMonitor) Watcher() {
	discovery := time.Tick(time.Second * 5)
	checkStat := time.Tick(time.Millisecond * 500)

	for {
		select {
		case <-checkStat:
			for fileName, _ := range fm.fds {
				fm.ReadLines(fileName)
			}
		case <-discovery:
			// Check to see if the files exist now, start reading them
			// if we can, and watch them
			for fileName, _ := range fm.discover {
				if fm.OpenFile(fileName) == nil {
					delete(fm.discover, fileName)
				}
			}
		case <-fm.stopChan:
			for _, fd := range fm.fds {
				fd.Close()
			}
			return
		}
	}
}
开发者ID:hellcoderz,项目名称:heka,代码行数:26,代码来源:logfile_input.go

示例12: Watcher

// Runs in its own goroutine, listens for interval tickers which trigger it to
// a) try to open any upopened files and b) read any new data from already
// opened files.
func (fm *FileMonitor) Watcher() {
	discovery := time.Tick(fm.discoverInterval)
	checkStat := time.Tick(fm.statInterval)

	ok := true

	for ok {
		select {
		case _, ok = <-fm.stopChan:
			break
		case <-checkStat:
			if fm.fd != nil {
				ok = fm.ReadLines(fm.logfile)
				if !ok {
					break
				}
			}
		case <-discovery:
			// Check to see if the files exist now, start reading them
			// if we can, and watch them
			if fm.OpenFile(fm.logfile) == nil {
				fm.discover = false
			}
		}
	}
	if fm.fd != nil {
		fm.fd.Close()
		fm.fd = nil
	}
}
开发者ID:pchojnacki,项目名称:heka,代码行数:33,代码来源:logfile_input.go

示例13: get_headers

func get_headers() {
	if SeedNode != "" {
		pr, e := peersdb.NewPeerFromString(SeedNode)
		if e != nil {
			fmt.Println("Seed node error:", e.Error())
		} else {
			fmt.Println("Seed node:", pr.Ip())
			new_connection(pr)
		}
	}
	LastBlock.Mutex.Lock()
	LastBlock.node = MemBlockChain.BlockTreeEnd
	LastBlock.Mutex.Unlock()

	tickTick := time.Tick(100 * time.Millisecond)
	tickStat := time.Tick(6 * time.Second)

	for !GlobalExit() && !GetAllHeadersDone() {
		select {
		case <-tickTick:
			add_new_connections()

		case <-tickStat:
			LastBlock.Mutex.Lock()
			fmt.Println("Last Header Height:", LastBlock.node.Height, "...")
			LastBlock.Mutex.Unlock()
			usif_prompt()
		}
	}
}
开发者ID:niniwzw,项目名称:gocoin,代码行数:30,代码来源:hdrs.go

示例14: Updater

func (l *lgr) Updater(windowLogGranularity int, keyLogGranularity int) {
	go func() {
		// Fetch freshest logs
		c := time.Tick(
			time.Millisecond * time.Duration(windowLogGranularity),
		)
		for _ = range c {
			newWLogs := l.WindowLogger.GetFreshestTxtLogs()
			if newWLogs != nil {
				l.winLogs = append(
					l.winLogs,
					newWLogs,
				)
			}
		}
	}()

	go func() {
		// Fetch freshest logs
		c := time.Tick(
			time.Millisecond * time.Duration(keyLogGranularity),
		)
		for _ = range c {
			newKLogs := l.KeyLogger.GetFreshestNumLogs()
			if newKLogs != nil {
				l.keyLogs = append(
					l.keyLogs,
					newKLogs,
				)
			}
		}
	}()
}
开发者ID:erasche,项目名称:gologme,代码行数:33,代码来源:receiver.go

示例15: main

func main() {
	requests := make(chan int, 5)
	for i := 1; i <= 5; i++ {
		requests <- i
	}
	close(requests)
	limiter := time.Tick(time.Millisecond * 200)

	for req := range requests {
		<-limiter
		fmt.Println("request", req, time.Now())
	}
	burstyLimiter := make(chan time.Time, 3)

	for i := 0; i < 3; i++ {
		burstyLimiter <- time.Now()
	}

	go func() {
		for t := range time.Tick(time.Millisecond * 200) {
			burstyLimiter <- t
		}
	}()

	burstyRequests := make(chan int, 5)
	for i := 1; i <= 5; i++ {
		burstyRequests <- i
	}
	close(burstyRequests)
	for req := range burstyRequests {
		<-burstyLimiter
		fmt.Println("request", req, time.Now())
	}
}
开发者ID:erochest,项目名称:go-by-eg,代码行数:34,代码来源:rate-limiting.go


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