0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

現場で使える(どこでも使える)タイマー(ticker)

Last updated at Posted at 2020-11-07

何らかの処理を定期的に実行する場合にtickerを利用する方法

func main() {
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	for {
		select {
		case t := <-ticker.C:
			fmt.Println("Current time: ", t)
		}
	}
}

参考

応用

シグナルで停止する

func main() {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs)
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	for {
		select {
		case t := <-ticker.C:
			fmt.Println("Current time: ", t)
		case <-sigs:
			fmt.Println("done")
			return
		}
	}
}

他のチャネルと合わせる

func main() {
	c := make(chan int, 1)
	go func() {
		for i := 0; i < 10; i++ {
			time.Sleep(500 * time.Millisecond)
			c <- i
		}
		close(c)
	}()
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	for {
		select {
		case i, ok := <-c:
			if !ok {
				fmt.Println("done")
				return
			}
			fmt.Println("i = ", i)
		case t := <-ticker.C:
			fmt.Println("Current time: ", t)
		}
	}
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?