Created
January 7, 2016 01:12
-
-
Save tsujeeth/9bb2ad337a6404a76ec7 to your computer and use it in GitHub Desktop.
Example of setting a watch on modifications of a given file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"os" | |
"time" | |
) | |
func getLastModTime(filename string) time.Time { | |
fileInfo, err := os.Stat(filename) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return fileInfo.ModTime() | |
} | |
func NewFileWatcher(filename string, frequency time.Duration) chan time.Time { | |
c := make(chan time.Time) | |
go func() { | |
var lastMod time.Time = time.Now() | |
tick := time.Tick(frequency) | |
for _ = range tick { | |
currentMod := getLastModTime(filename) | |
if currentMod.After(lastMod) { | |
c <- currentMod | |
lastMod = currentMod | |
} | |
} | |
}() | |
return c | |
} | |
func main() { | |
watcher := NewFileWatcher("file_update.go", time.Second*5) | |
for t := range watcher { | |
log.Println("File updated! ", t) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment