Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7.  
  8. "github.com/go-fsnotify/fsnotify"
  9. )
  10.  
  11. //
  12. var watcher *fsnotify.Watcher
  13.  
  14. // main
  15. func main() {
  16.  
  17. // creates a new file watcher
  18. watcher, _ = fsnotify.NewWatcher()
  19. defer watcher.Close()
  20.  
  21. go watchPeriodically("/path/to/directory", 5)
  22.  
  23. //
  24. done := make(chan bool)
  25.  
  26. //
  27. go func() {
  28. for {
  29. select {
  30. // watch for events
  31. case event := <-watcher.Events:
  32. fmt.Printf("EVENT! %#v\n", event)
  33.  
  34. // watch for errors
  35. case err := <-watcher.Errors:
  36. fmt.Println("ERROR", err)
  37. }
  38. }
  39. }()
  40.  
  41. <-done
  42. }
  43.  
  44. // watchDir gets run as a walk func, searching for directories to add watchers to
  45. func watchDir(path string, fi os.FileInfo, err error) error {
  46.  
  47. // since fsnotify can watch all the files in a directory, watchers only need
  48. // to be added to each nested directory
  49. if fi.Mode().IsDir() {
  50. return watcher.Add(path)
  51. }
  52.  
  53. return nil
  54. }
  55.  
  56. // watchPeriodically adds sub directories peridically to watch, with the help
  57. // of fsnotify which maintains a directory map rather than slice.
  58. func watchPeriodically(directory string, interval int) {
  59. done := make(chan struct{})
  60. go func() {
  61. done <- struct{}{}
  62. }()
  63. ticker := time.NewTicker(time.Duration(interval) * time.Second)
  64. defer ticker.Stop()
  65. for ; ; <-ticker.C {
  66. <-done
  67. if err := filepath.Walk(directory, watchDir); err != nil {
  68. fmt.Println(err)
  69. }
  70. go func() {
  71. done <- struct{}{}
  72. }()
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement