golang 1.20.13 定时执行bat shell 脚本

golang 1.20.13 定时执行bat shell 脚本

package main

import (
    "fmt"
   _ "github.com/CodyGuo/godaemon"
    "os/exec"
    "time"
)

func main() {
    // 设置定时任务的时间
    t := time.Now()
    next := time.Date(t.Year(), t.Month(), t.Day(), 13, 53, 0, 0, t.Location())
    if t.After(next) { // 如果现在已经是今天的17点之后,则设置为明天的17点
        next = next.AddDate(0, 0, 1)
    }

    // 计算下次执行的等待时间
    d := next.Sub(t)

    // 启动定时器
    time.AfterFunc(d, func() {
        for {
            // 执行批处理脚本
            cmd := exec.Command("E:\\tables\\LoggerOperate_sql.bat")
            err := cmd.Run()
            if err != nil {
                fmt.Printf("Error: %s\n", err)
            }

            // 等待一天结束,然后再次执行
            time.Sleep(24 * time.Hour)
        }
    })

    // 阻塞主goroutine
    select {}
}

 

go build -o .\cron_LoggerOperate.exe -ldflags "-s -w -H=windowsgui" .\cron.go

posted @ 2024-04-26 13:55  zhaoguanhao  阅读(31)  评论(0编辑  收藏  举报