Go监控目录变化小程序.

来源:互联网 时间:1970-01-01


package mainimport ("flag""log""os/exec""strings""sync""time""github.com/go-fsnotify/fsnotify")var (sleeptime intpath stringcmd stringargs []string)func init() {flag.IntVar(&sleeptime, "t", 30, "-t=30")flag.StringVar(&path, "p", "./", "-p=filepath or dirpath")flag.StringVar(&cmd, "c", "", "-c=command")str := flag.String("a", "", `-a="args1 args2"`)flag.Parse()args = strings.Split(*str, " ")}func main() {Watch, err := fsnotify.NewWatcher()if err != nil {log.Println("Init monitor error: ", err.Error())return}if err := Watch.Add(path); err != nil {log.Println("Add monitor path error: ", path)return}var (cron bool = falselock = new(sync.Mutex))for {select {case event := <-Watch.Events:log.Printf("Monitor event %s", event.String())if !cron {cron = truego func() {T := time.After(time.Second * time.Duration(sleeptime))<-Tif err := call(cmd, args...); err != nil {log.Println(err)}lock.Lock()cron = falselock.Unlock()}()}case err := <-Watch.Errors:log.Println(err)return}}}func call(programe string, args ...string) error {cmd := exec.Command(programe, args...)buf, err := cmd.Output()if err != nil {return err}log.Printf("/n%s/n", string(buf))return nil}

版权声明:本文为博主原创文章,未经博主允许不得转载。



相关阅读:
Top