- 公司要求场景,由于公司经理没有空闲时间写,所以(求人不如求己)自己鼓捣了一下搞定要求 : 在windows里面需要分别调用4个url,两个url间隔5分钟调用一次,两个url间隔10分钟调用一次
- 这里我们使用go语言的
github.com/robfig/cron
定时任务包,go get github.com/robfig/cron
,以下是代码实现
package main
import (
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
cron "github.com/robfig/cron"
)
func main() {
crontab := cron.New()
fun1 := func() {
t4 := time.Now().Hour()
if t4 >= 3 && t4 <= 21 {
fmt.Println("-------------开始调用------")
url := "localhost/index/index/index"
getUrl(url)
}
}
spec := "0 */5 * * * ?"
crontab.AddFunc(spec, fun1)
go crontab.Start()
defer crontab.Stop()
select {}
}
func getUrl(url string) {
t := time.Now()
req, _ := http.NewRequest("GET", url, nil)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
resu := string(body)
fmt.Println(resu)
fmt.Printf("执行时间: %d-%d-%d %d:%d:%d\n", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
}
- 编写之后,使用打包命令:
go build main.go
获得main.exe之后点击运行就好了