代码文件timer.go:
package main import ( "bytes" "fmt" "github.com/unknwon/goconfig" "os/exec" "time" ) var config *goconfig.ConfigFile func init() { path := "./config.ini" conf, err := goconfig.LoadConfigFile(path) if err != nil { fmt.Println(err) } config = conf } func main() { t := time.NewTicker(1 * time.Second) for { select { case <-t.C: run() } } } func run() { startTimestamp, _ := config.Int64("time", "startTimestamp") loopSeconds, _ := config.Int64("time", "loopSeconds") unix := time.Now().Unix() if startTimestamp <= unix && (unix-startTimestamp)%loopSeconds == 0 { cmd() } } func cmd() { scriptBinPath, _ := config.GetValue("cmd", "scriptBinPath") filepath, _ := config.GetValue("cmd", "filePath") params, _ := config.GetValue("cmd", "params") cmd := exec.Command(scriptBinPath, filepath, params) var out bytes.Buffer cmd.Stdout = &out err := cmd.Start() if err != nil { fmt.Println(err) } fmt.Println("Waiting for command to finish...") err = cmd.Wait() if err != nil { fmt.Printf("Command finished with error: %v", err) } fmt.Println(out.String()) }
配置文件config.ini放在代码生成可执行文件同级目录
[time] ;开始的时间戳 startTimestamp:1396361928 ;循环的时间间隔 loopSeconds:3 [cmd] ;执行的脚本 scriptBinPath:E:/zendloader+redis+iis/php-5.3.28-nts-Win32-VC9-x86/php.exe ;被执行的文件 filePath:D:/jianguo/command/application/command/demo.php ;参数 params:
有疑问加站长微信联系(非本文作者)