Skip to content

Instantly share code, notes, and snippets.

Created October 4, 2013 09:34
Show Gist options
  • Save anonymous/6823411 to your computer and use it in GitHub Desktop.
Save anonymous/6823411 to your computer and use it in GitHub Desktop.
[iProg] 一个例子,有助于大家学习channel,不多说,直接上代码!这个例子是定时检查【当前时间】和【lastHeartBeatTime】的时间段值,小于6秒输出“is alive” ,大于6秒输出程序结束!
package main
import (
"fmt"
"time"
)
var lastHeartBeatTime time.Time
var checkChan chan bool
var checkoutChan chan bool
var out chan int
func main() {
checkChan = make(chan bool)
checkoutChan = make(chan bool)
out = make(chan int)
lastHeartBeatTime = time.Now()
fmt.Println(lastHeartBeatTime.Format("2006-01-02 15:04:05"))
fmt.Println()
dd := time.NewTimer(time.Second * 1)
<-dd.C
go CheckTimeOut()
d := time.NewTimer(time.Second * 1)
<-d.C
checkChan <- true
<-out
}
func CheckTimeOut() {
timeoutflag := 0
var ticker *time.Ticker
for {
select {
case ch := <-checkChan:
if ch {
go func() {
ticker = time.NewTicker(time.Second)
defer ticker.Stop()
for t := range ticker.C {
fmt.Println(t.Format("2006-01-02 15:04:05"))
isTimeOut()
}
}()
}
case sh := <-checkoutChan:
if sh {
if ticker != nil {
ticker.Stop()
fmt.Println("timer stop")
timeoutflag = 1
}
}
}
if timeoutflag == 1 {
break
}
}
fmt.Println("func end")
out <- 1
}
func isTimeOut() {
duration := time.Now().Sub(lastHeartBeatTime)
if duration.Seconds() >= 6 {
fmt.Println(duration, " ----- break Connection!")
fmt.Println()
checkoutChan <- true
} else {
fmt.Println(duration, " ----- is alive!")
fmt.Println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment