gorutine
とtime
パッケージのTicker
を使ってバックグラウンドで定期処理を実行することができます。
本サンプルでは、1秒間隔のTicker
を生成して、現在時刻を表示します。
5秒後にTicker停止用のメッセージがチャネルに送られて、Ticker
をstopしています
■サンプルコード
package main import ( "fmt" "time" ) func main() { chStop := make(chan int, 1) timerfunc(chStop) time.Sleep(time.Second * 5) chStop <- 0 // Tickerをstopさせるメッセージ close(chStop) time.Sleep(time.Second * 1) fmt.Println("Application End.") } func timerfunc(stopTimer chan int) { go func() { ticker := time.NewTicker(1 * time.Second) // 1秒間隔のTicker LOOP: for { select { case <-ticker.C: fmt.Printf("now -> %v\n", time.Now()) case <-stopTimer: fmt.Println("Timer stop.") ticker.Stop() break LOOP } } fmt.Println("timerfunc end.") }() }
■実行結果
now -> 2017-04-27 06:03:55.7592988 +0900 JST now -> 2017-04-27 06:03:56.7592988 +0900 JST now -> 2017-04-27 06:03:57.7592988 +0900 JST now -> 2017-04-27 06:03:58.7592988 +0900 JST now -> 2017-04-27 06:03:59.7592988 +0900 JST Timer stop. timerfunc end. Application End.
というわけで1秒間隔で現在時刻が表示される処理ができました