借助 gocron 可以在web server 里运行定时任务
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
package main
import (
"fmt"
"net/http"
"github.com/jasonlvhit/gocron"
"github.com/zenazn/goji"
)
func taskWithParams(a int, b string) {
fmt.Println(a, b)
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
}
func main() {
gocron.Every(1).Second().Do(taskWithParams, 1, "hello")
go gocron.Start()
goji.Get("/", hello)
goji.Serve()
}
gocron https://github.com/jasonlvhit/gocron
更多 gocron 使用示例:
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"fmt"
"github.com/jasonlvhit/gocron"
)
func task() {
fmt.Println("I am runnning task.")
}
func taskWithParams(a int, b string) {
fmt.Println(a, b)
}
func main() {
// Do jobs with params
gocron.Every(1).Second().Do(taskWithParams, 1, "hello")
// Do jobs without params
gocron.Every(1).Second().Do(task)
gocron.Every(2).Seconds().Do(task)
gocron.Every(1).Minute().Do(task)
gocron.Every(2).Minutes().Do(task)
gocron.Every(1).Hour().Do(task)
gocron.Every(2).Hours().Do(task)
gocron.Every(1).Day().Do(task)
gocron.Every(2).Days().Do(task)
// Do jobs on specific weekday
gocron.Every(1).Monday().Do(task)
gocron.Every(1).Thursday().Do(task)
// function At() take a string like 'hour:min'
gocron.Every(1).Day().At("10:30").Do(task)
gocron.Every(1).Monday().At("18:30").Do(task)
// remove, clear and next_run
_, time := gocron.NextRun()
fmt.Println(time)
// gocron.Remove(task)
// gocron.Clear()
// function Start start all the pending jobs
<-gocron.Start()
// also , you can create a your new scheduler,
// to run two scheduler concurrently
s := gocron.NewScheduler()
s.Every(3).Seconds().Do(task)
<-s.Start()
}
本文网址: https://golangnote.com/topic/106.html 转摘请注明来源