/*通過newtimer和newticker分別實現定時器*/
package main
import (
"fmt"
"time"
)func main() */
fmt.println(time.now().utc(), "starting....")
timer := time.newtimer(time.second * 2) //定時2s
ticker := time.newticker(time.second * 5)
bools := make(chan bool)
go func(t1 *time.timer, t2 *time.ticker)
case <-t2.c:
fmt.println(time.now().utc(), "ticker-5s已到\n")
t2.reset(time.second * 5)
}} }(timer, ticker) //將timer與ticker作為實參傳入
time.sleep(11 * time.second)
bools <- true //true存入管道bools時,select迴圈中stop會出現值,所以退出select迴圈
close(bools)
time.sleep(1 * time.second)
}
package main
import (
"log"
"os"
"os/exec"
"runtime"
"strconv"
)func processid() else if "windows" == systype
output, err := command.output()
if err != nil
log.printf("current process info:\n%s", string(output))
}func main()
//參考:github.com/bigwhite/experiments/redis-cluster-distributed-lock
//uuid,用於生成redis分布式鎖的值
func fuuid() (string,error)
func getisleader() int64
func getredisval(client *goredislib.clusterclient) string
func trytobecomeleader(client *goredislib.clusterclient) (bool, func() (bool, error), error)
return true, func() (bool, error) else
}, nil
}func doelectionandmaintainthestatus(c *goredislib.clusterclient, quit <-chan struct{}) , nil*/
}if !ok || err != nil
} else
case <-quit:
return
} }}func main() ) //空結構體,讀取close的channel,返回零
<-quit)
client := goredislib.newclusterclient(&goredislib.clusteroptions)
defer client.close()
go func() ()
c := make(chan os.signal, 1) //可放入1個訊號
signal.notify(c, syscall.sigint, syscall.sigterm) //監聽中斷訊號ctrl+c,管道c接受訊號,syscall.sigint, syscall.sigterm為要監聽的訊號(不設定-監聽所有訊號)
// block until a signal is received阻塞直到接收到中斷訊號
s := <-c
close(quit) //quit通道會返回0,doelectionandmaintainthestatus中的select檢測到quit有值,則會停止
log.printf("recv exit signal...", s)
wg.wait()//等待go func執行緒結束
log.printf("program exit ok")
}
go 語言中的定時器
在日常的開發過程中,我們免不了與定時器打交道。通常需要定時執行某個程式,可能是每隔一段時間執行一次,也可能是固定的每天在某乙個時間點執行一次。總之,定時器的使用是非常頻繁的,下面將介紹幾種常用定時器。1.假設每隔三秒,我們列印一段資訊,可以採用如下方式。我們將要執行的程式放在乙個go協程中去執行。p...
定時器簡單應用(掛起程序)
include include include include include struct timer list stimer 定義定時器 int timeout 10 hz static void time handler unsigned long data static int init t...
知識小結 04go語言定時器
1 go channel channel是golang在語言層面提供的goroutine間的通訊方式,比unix管道更易用也更輕便。channel主要用於程序內各goroutine間通訊,如果需要跨程序通訊,建議使用分布式系統的方法來解決。注 channel可以看作是乙個公共佇列,也可以當成公共佇列...