go countdown

1. 倒计时countdown

例子还是来自go programing language。基本上是对time.Tick 加select的简单应用。

2.countdown 1

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("commencing countdown.")
	tick := time.Tick(1 * time.Second)
	for countdown := 10; countdown > 0; countdown-- {
		fmt.Println(countdown)
		<-tick
	}
	//launch()

}

一个倒数程序,里面的关键是tick := time.Tick(1*time.second) ,这个tick每1秒产生一个channel,在for里循环调用即可,<-tick没收到channel会阻塞。

3. countdown2 ,带cancel。

package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	fmt.Println("commencing down")
	//tick:=time.Tick(1*time.Second)
	abort := make(chan struct{})
	go func() {
		os.Stdin.Read(make([]byte, 1))
		abort <- struct{}{}
	}()

	select {
	case <-time.After(10 * time.Second):

	case <-abort:
		fmt.Println("lauch aborted!")
		return
	}

}
		

如果要取消,就需要增加一个channel,这样就需要select-case来处理这种情况。以上是abort在time.After之前触发就会直接return。

4.countdown

package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	fmt.Println("commencing down")
	tick := time.Tick(1 * time.Second)
	abort := make(chan struct{})
	go func() {
		os.Stdin.Read(make([]byte, 1))
		abort <- struct{}{}
	}()
	for countdown := 10; countdown > 0; countdown-- {
		fmt.Println(countdown)
		select {
		case <-tick:

		case <-abort:
			fmt.Println("lauch aborted!")
			return
		}
	}

}

第三个是用回tick ,不用time.After了。

tick非常好用,但是想对他生命周期进行管理,就需要NewTicker

ticker := time.NewTicker(1*time.Second)
<- ticker.C
ticker.Stop()

这样可以stop 这个ticker。

默认的time.Ticker()

// Tick is a convenience wrapper for NewTicker providing access to the ticking
// channel only. While Tick is useful for clients that have no need to shut down
// the Ticker, be aware that without a way to shut it down the underlying
// Ticker cannot be recovered by the garbage collector; it "leaks".
// Unlike NewTicker, Tick will return nil if d <= 0.
func Tick(d Duration) <-chan Time {
	if d <= 0 {
		return nil
	}
	return NewTicker(d).C
}

time.Tick就是对time.NewTicker的简单封装。返回channel,并不能stop,对时间进行了判断小于0就返回nil。

原文地址:https://www.cnblogs.com/gqdw/p/13064183.html