golang定時器實現

2021-10-01 23:27:14 字數 2087 閱讀 4798

golang定時器,需求是能夠在指定時間後停止。或某種條件出發停止。

好,下面上貨。

package main

import (

"context"

"fmt"

"sync"

"time"

)func main()

func stoptheworld()

func goclock() ()

for }}

func goclock2()

}}

執行結果:

123

clock2 current time: 2020-01-07 10:46:19.122178 +0800 cst m=+1.003391336

clock current time: 2020-01-07 10:46:19.122301 +0800 cst m=+1.003513931

clock2 current time: 2020-01-07 10:46:20.121693 +0800 cst m=+2.002832908

clock current time: 2020-01-07 10:46:20.121726 +0800 cst m=+2.002866446

clock2 current time: 2020-01-07 10:46:21.1248 +0800 cst m=+3.005867116

clock current time: 2020-01-07 10:46:21.1248 +0800 cst m=+3.005866846

clock2 current time: 2020-01-07 10:46:22.1235 +0800 cst m=+4.004567391

clock current time: 2020-01-07 10:46:22.123503 +0800 cst m=+4.004569986

clock2 current time: 2020-01-07 10:46:23.119886 +0800 cst m=+5.000879581

clock current time: 2020-01-07 10:46:23.119885 +0800 cst m=+5.000878736

clock2 current time: 2020-01-07 10:46:24.119906 +0800 cst m=+6.000899833

clock current time: 2020-01-07 10:46:24.119945 +0800 cst m=+6.000938638

clock current time: 2020-01-07 10:46:25.121888 +0800 cst m=+7.002808593

clock2 current time: 2020-01-07 10:46:25.121927 +0800 cst m=+7.002847958

clock current time: 2020-01-07 10:46:26.119995 +0800 cst m=+8.000842811

clock2 current time: 2020-01-07 10:46:26.119992 +0800 cst m=+8.000840493

clock2 current time: 2020-01-07 10:46:27.120127 +0800 cst m=+9.000975136

clock current time: 2020-01-07 10:46:27.120108 +0800 cst m=+9.000956121

clock current time: 2020-01-07 10:46:28.122912 +0800 cst m=+10.003686127

done!

clock2 current time: 2020-01-07 10:46:28.122912 +0800 cst m=+10.003686386

done!

簡單總結一下,個人推薦使用context,因為能夠更加方便控制定時器的停止時間,同時還可以在每次執行定時器業務邏輯的時候進行判斷是否達到定時器的停止條件,從而停止計時器。

golang中的定時器

type timer struct乙個定時器,代表未來的乙個單一事件,你可以告訴timer你要等待多長時間,它提供乙個channel,在將來的那個時間channel提供了乙個時間值 time.newtimer時間到了,只響應一次 func main time.after 2 time.second ...

Golang之定時器,recover

滴答滴答 定時器的使用 package main import fmt time 定時器的使用 func main 一次定時器 package main import fmt time 定時器的使用 func main 超時控制 package main import fmt time func q...

Golang 定時器timer和ticker

兩種型別的定時器 ticker和timer。兩者有什麼區別呢?請看如下 package main import fmt time func main output timeout timeout timeout 解析 ticker只要定義完成,從此刻開始計時,不需要任何其他的操作,每隔固定時間都會觸...