go循环执行外部命令

package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os/exec"
	"strings"
	"time"
)

type Config struct {
	Command  string `json:"command"`
	Duration string `json:"duration"`
}

func Do(command string) {
	s := strings.Split(command, " ")

	args := make([]string, 0)
	for i := 1; i < len(s); i++ {
		args = append(args, s[i])
	}

	cmd := exec.Command(s[0], args...)
	buf, err := cmd.Output()
	if err != nil {
		log.Println(err)
		return
	}

	log.Println(command+":", string(buf))
}

func timeFunc(f func(s string), t *time.Ticker, command string, c chan bool) {
	for {
		select {
		case <-t.C:
			f(command)
		}
	}

	<-c
}

func readConfig() []Config {
	b, err := ioutil.ReadFile("time.conf")
	if err != nil {
		log.Println("读取文件失败:%s", err)
		return nil
	}

	var conf []Config
	err = json.Unmarshal(b, &conf)
	if err != nil {
		log.Printf("序列化文件失败:%s", err)
		return nil
	}

	return conf
}

func getConfigValue(conf []Config, c chan bool) {
	for _, v := range conf {
		d, err := time.ParseDuration(v.Duration)
		if err != nil {
			log.Printf("duration格式错误:%s", err)
		}
		t := time.NewTicker(d)
		go timeFunc(Do, t, v.Command, c)
	}
}

func main() {
	conf := readConfig()

	c := make(chan bool)

	getConfigValue(conf, c)

	c <- true
}

  因为go的ticker可以作为chan来使用,for range便可实现循环执行,如果需要做定时的话,就是获取当前时间,然后时间到了再执行。

配置文件:

[
    {
        "command":"ls -l",
        "duration":"1s"
    },
    {
        "command":"pwd",
        "duration":"2s"
    }
]

  

posted @ 2016-11-07 17:06  ZJJ2DSN  阅读(285)  评论(0编辑  收藏  举报