golang 计划任务和windows下服务安装,删除

蜗牛MVP · · 1931 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

网站开始使用的是win服务器系统计划任务,添加 XX.bat,设置执行时间

xx.bat中的内容:

C:\php\php.exe -q C:\WWW\api\script\AutoCancelOrder.php

目前这种方式是可以正常运行的,最近在看了golang以后,打算使用golang来重新计划任务

cron.go代码如下,go run 之前需要 go get -u github.com/jakecoffman/cron

package main

import (
"fmt"
"github.com/jakecoffman/cron"
"io/ioutil"
"net/http"
"net/url"
"os"
"time"
)

func main() {
var c = cron.New()
spec := "0 41 "
c.AddFunc(spec, func() {
autoTongji()
}, "autoTongji")

spec = "*/15 * 9-17 * * ?"
c.AddFunc(spec, func() {
    autoFddsign()
}, "autoFddsign")
c.Start()

select {}

}

//每日数据统计 0:30执行一次
func autoTongji() {
log := fmt.Sprintf("--Tongji 执行时间:%s, \n", time.Now().Format("2006-01-02 15:04:05"))
writelog(log)
}

//法大大签章
func autoFddsign() {
log1 := fmt.Sprintf("--FddSign 执行时间:%s, \n", time.Now().Format("2006-01-02 15:04:05"))
writelog(log1)
}

func request(request string) (rtn string) {
u, := url.Parse(request)
q := u.Query()
q.Set("token", "site@@crontab")
u.RawQuery = q.Encode()
reponse,
:= http.Get(u.String())
result, _ := ioutil.ReadAll(reponse.Body)
reponse.Body.Close()
result_str := string(result)
return result_str
}

//写入日志
func writelog(log string) {
logdir := "log"

var path string
if os.IsPathSeparator('\\') {
    path = "\\"
} else {
    path = "/"
}

dir, _ := os.Getwd()
os.Mkdir(dir+path+logdir, os.ModePerm)

file_path := dir + path + logdir + path + time.Now().Format("2006-01") + ".txt"
_, err := os.Stat(file_path)
if err != nil {
    f, _ := os.Create(file_path)
    defer f.Close()
}

f, _ := os.OpenFile(file_path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
f.WriteString(log)

f.Close()

}

func checkErr(err error) {
if err != nil {
fmt.Println(err.Error())
panic(err)
}
}
运行结果查看:


TIM截图20170602091555.jpg

第二步使用nssm安装和删除服务
install.bat 安装服务,此处要用绝对路径

nssm install ddAuto F:\golang\src\cron.exe
nssm start ddAuto

delete.bat:删除服务
nssm stop ddAuto
nssm remove ddAuto

代码贴出来有点变形了。。将就这看。。。

至于 spec = "/15 9-17 ?" 时间的设置,可以参考下linux crontab的使用方法,golang cron 比 crontab多了个秒单位设置


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:蜗牛MVP

查看原文:golang 计划任务和windows下服务安装,删除

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1931 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传