Go 常用代码块

总结备忘一下常用的的 Go 代码片段

遍历目录下的文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func getFilelist(root string) {
err := filepath.Walk(root, func(path string, file os.FileInfo, err error) error {
if file == nil {
return nil
}
if path == root || file.IsDir() {
return nil
}
fmt.Println(path)
return nil
})
if err != nil {
fmt.Printf("filepath.Walk() returned %v\n", err)
}
}

定时器

1
2
3
4
5
6
7
8
9
10
11
duration := 2 * time.Second
timer := time.NewTimer(duration)
go func() {
for {
select {
case <-timer.C:
fmt.Println("here")
timer.Reset(duration)
}
}
}()

定时执行任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package main

import (
"fmt"
"time"
)

const INTERVAL_PERIOD time.Duration = 24 * time.Hour

const HOUR_TO_TICK int = 23
const MINUTE_TO_TICK int = 00
const SECOND_TO_TICK int = 03

func main() {
ticker := updateTicker()
for {
<-ticker.C
fmt.Println(time.Now(), "- just ticked")
ticker = updateTicker()
}
}

func updateTicker() *time.Ticker {
nextTick := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), HOUR_TO_TICK, MINUTE_TO_TICK, SECOND_TO_TICK, 0, time.Local)
if !nextTick.After(time.Now()) {
nextTick = nextTick.Add(INTERVAL_PERIOD)
}
fmt.Println(nextTick, "- next tick")
diff := nextTick.Sub(time.Now())
return time.NewTicker(diff)
}
欣赏此文?求鼓励,求支持!
显示 Disqus 评论
0%