/
fileWatcher.go
100 lines (85 loc) Β· 2.5 KB
/
fileWatcher.go
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
// Copyright 2020 Thomas.Hoehenleitner [at] seerose.net
// Use of this source code is governed by a license that can be found in the LICENSE file.
package id
import (
"fmt"
"io"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/rokath/trice/pkg/msg"
"github.com/spf13/afero"
)
// FileWatcher checks the id list file for changes.
// taken from https://medium.com/@skdomino/watch-this-file-watching-in-go-5b5a247cf71f
func (lu TriceIDLookUp) FileWatcher(w io.Writer, fSys *afero.Afero, m *sync.RWMutex) {
// creates a new file watcher
watcher, err := fsnotify.NewWatcher()
msg.FatalOnErr(err)
defer func() { msg.OnErr(watcher.Close()) }()
done := make(chan bool)
go func() {
var now, last time.Time
for {
select {
// watch for events
case event, ok := <-watcher.Events:
fmt.Fprintln(w, "EVENT:", event, ok, time.Now().UTC())
now = time.Now()
diff := now.Sub(last)
if diff > 5000*time.Millisecond {
fmt.Fprintln(w, "refreshing id.List")
m.Lock()
msg.FatalOnErr(lu.fromFile(fSys, FnJSON))
lu.AddFmtCount(w)
m.Unlock()
last = time.Now()
}
// watch for errors
case err := <-watcher.Errors:
fmt.Fprintln(w, "ERROR1", err, time.Now().UTC())
}
}
}()
// out of the box fsnotify can watch a single file, or a single directory
msg.InfoOnErr(watcher.Add(FnJSON), "ERROR2")
if Verbose {
fmt.Fprintln(w, FnJSON, "watched now for changes")
}
<-done
}
// FileWatcher checks the id location information file for changes.
// taken from https://medium.com/@skdomino/watch-this-file-watching-in-go-5b5a247cf71f
func (li TriceIDLookUpLI) FileWatcher(w io.Writer, fSys *afero.Afero) {
// creates a new file watcher
watcher, err := fsnotify.NewWatcher()
msg.FatalOnErr(err)
defer func() { msg.OnErr(watcher.Close()) }()
done := make(chan bool)
go func() {
var now, last time.Time
for {
select {
// watch for events
case event, ok := <-watcher.Events:
fmt.Fprintln(w, "EVENT:", event, ok, time.Now().UTC())
now = time.Now()
diff := now.Sub(last)
if diff > 5000*time.Millisecond {
fmt.Fprintln(w, "refreshing li list")
msg.FatalOnErr(li.fromFile(fSys, LIFnJSON))
last = time.Now()
}
// watch for errors
case err := <-watcher.Errors:
fmt.Fprintln(w, "ERROR1", err, time.Now().UTC())
}
}
}()
// out of the box fsnotify can watch a single file, or a single directory
msg.InfoOnErr(watcher.Add(LIFnJSON), "ERROR2")
if Verbose {
fmt.Fprintln(w, LIFnJSON, "watched now for changes")
}
<-done
}