GolangNote

Golang笔记

借助gocron 可以在web server 里运行定时任务

Permalink

借助 gocron 可以在web server 里运行定时任务

Go: 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
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 使用示例:

Go: 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 转摘请注明来源

Related articles

golang 实现的基于web的文件管理-filebrowser

FileBrowser 在指定目录中提供了一个文件管理界面,可用于上传,删除,预览,重命名和编辑文件。它允许创建多个用户,每个用户都可以有自己的目录。它可以用作独立的应用程序。...

Golang Web 程序生产环境独立部署示例

一个 web 应用通常是跑在一个前端代理,如 Nginx 后,这样可以方便的在同一个服务器部署多个应用。这里说的独立部署是指让 go web 程序直接暴露在外面,独占 443、80 端口(俗称裸跑)。这样做除了性能有些提高外,更重要的是部署方便。...

Write a Comment to "借助gocron 可以在web server 里运行定时任务"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms