Skip to content

Instantly share code, notes, and snippets.

@tsujeeth
Created January 7, 2016 01:12
Show Gist options
  • Save tsujeeth/9bb2ad337a6404a76ec7 to your computer and use it in GitHub Desktop.
Save tsujeeth/9bb2ad337a6404a76ec7 to your computer and use it in GitHub Desktop.
Example of setting a watch on modifications of a given file
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