概述

golang有三种方式实现定时器:

  • ticker
  • timer
  • select

Ticker

通过 time.NewTicker(d)的方式实现定时器

	d := time.Duration(time.Second * 2)
	t1 := time.NewTicker(d)
	defer t1.Stop()
	go func() {
		for  {
			<- t1.C
			fmt.Println("NewTicker...")
		}
	}()

Timer

通过 time.NewTimer(d)的方式实现定时器

	t2 := time.NewTimer(d)
	defer t2.Stop()
	go func() {
		for {
			<- t2.C
			fmt.Println("NewTimer...")
		}
	}()

select

通过select的方式实现定时器:

for {
		select {
		case <- time.After(d):
			fmt.Println("select...")
		}
	}

三种定时器示例代码

package main

import (
	"fmt"
	"time"
)

func main() {
	d := time.Duration(time.Second * 2)
	t1 := time.NewTicker(d)
	defer t1.Stop()
	go func() {
		for  {
			<- t1.C
			fmt.Println("NewTicker...")
		}
	}()

	t2 := time.NewTimer(d)
	defer t2.Stop()
	go func() {
		for {
			<- t2.C
			fmt.Println("NewTimer...")
		}
	}()

	for {
		select {
		case <- time.After(d):
			fmt.Println("select...")
		}
	}
}

--完--