服务器之家

服务器之家 > 正文

golang监听文件变化的实例

时间:2021-04-20 00:58     来源/作者:雪东~

废话不多说,直接上官网demo

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main
import (
    "log"
    "github.com/fsnotify/fsnotify"
)
func main() {
    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        log.Fatal(err)
    }
    defer watcher.Close()
    done := make(chan bool)
    go func() {
        for {
            select {
            case event, ok := <-watcher.Events:
                if !ok {
                    return
                }
                log.Println("event:", event)
                if event.Op&fsnotify.Write == fsnotify.Write {
                    log.Println("modified file:", event.Name)
                }
            case err, ok := <-watcher.Errors:
                if !ok {
                    return
                }
                log.Println("error:", err)
            }
        }
    }()
    err = watcher.Add("/tmp/foo")
    if err != nil {
        log.Fatal(err)
    }
    <-done
}

补充:golang监控文件变化,git自动提交代码

代码如下:

如果文件有变动,且10分钟内,没有再次变动,则提交代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main
import (
 "fmt"
 _ "fmt"
 "github.com/fsnotify/fsnotify"
 "log"
 "os"
 "os/exec"
 "path/filepath"
 "time"
)
 
//if the conditions are met, execute the shell script
func execCmd() {
 cmd := exec.Command("/root/nfs_bak_pro/nfs.git.sh")
 err := cmd.Run()
 if err != nil {
 fmt.Println("Execute Command failed:" + err.Error())
 return
 }
 fmt.Println("Execute Command finished.")
}
 
//handle folder files changed event
func watchFiles(watcher *fsnotify.Watcher, ch chan int64) {
 for {
 select {
 case ev := <-watcher.Events: {
 isNotify := false
 
 if ev.Op & fsnotify.Create == fsnotify.Create {
  log.Println("create : ", ev.Name)
  isNotify = true
 
  file, err := os.Stat(ev.Name)
  if err == nil && file.IsDir() {
  watcher.Add(ev.Name)
  fmt.Println("add watch : ", ev.Name)
  }
 }
 
 if ev.Op & fsnotify.Remove == fsnotify.Remove {
  log.Println("delete : ", ev.Name)
  isNotify = true
  err := watcher.Remove(ev.Name)
  fmt.Printf("remove watch: %s, err: %v\n", ev.Name, err)
 }
 
 if ev.Op & fsnotify.Rename == fsnotify.Rename {
  log.Println("rename : ", ev.Name)
  if "" != ev.Name {
  isNotify = true
  err := watcher.Remove(ev.Name)
  fmt.Printf("remove watch: %s, err: %v\n", ev.Name, err)
  }
 }
 
 if isNotify {
  ch <- time.Now().Unix()
 }
 }
 case err := <-watcher.Errors: {
 log.Println("watcher error : ", err)
 return
 }
 }
 }
}
 
//if folder event met, execute the shell script after 10minutes
func watchTime(ch chan int64) {
 var timer *time.Timer
 for {
 select {
 case <- ch:{
 if nil != timer {
  log.Printf("reset timer")
  timer.Stop()
 }
 timer = time.NewTimer(10 * 60 * time.Second)
 go func() {
  <-timer.C
  execCmd()
 }()
 }
 }
 }
}
 
//watch the folder and sub folders
func WatchDir(watcher *fsnotify.Watcher, dir string) {
 filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
 if info.IsDir() {
 path, err := filepath.Abs(path)
 if err != nil {
 return err
 }
 err = watcher.Add(path)
 if err != nil {
 return err
 }
 }
 return nil
 })
}
 
func main() {
 notifyCh := make(chan int64)
 watcher, err := fsnotify.NewWatcher()
 if err != nil {
 log.Fatal(err)
 }
 defer watcher.Close()
 
 WatchDir(watcher, "/data/nfs")
 go watchFiles(watcher, notifyCh)
 go watchTime(notifyCh)
 select {}
}

shell 脚本如下

?
1
2
3
4
5
6
7
8
#!/bin/bash
 
cd /root/nfs_bak_pro/nfs.git
log_file=/root/nfs_bak_pro/nfs_git_`date +"%Y%m%d"`.log
 
git add --all . >> $log_file
git commit -a -m "`date +"%Y-%m-%d %H:%M:%S"`" >> $log_file
git push origin master >> $log_file

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/weixin_39998006/article/details/106854551

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
返回顶部