To remove watching, we can use the Remove method, which will remove watching for the entire file/directory.

When there are multiple watching callbacks for the same file/directory, we can remove a specified callback using the RemoveCallback method. The callbackId parameter is the unique ID returned by the Callback object when adding watching.

Example 1

  1. package main
  2. import (
  3. "context"
  4. "time"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gfsnotify"
  7. "github.com/gogf/gf/v2/os/gtimer"
  8. )
  9. func main() {
  10. var (
  11. ctx = context.Background()
  12. logger = g.Log()
  13. )
  14. c1, err := gfsnotify.Add("/home/john/temp/log", func(event *gfsnotify.Event) {
  15. logger.Debug(ctx, "callback1")
  16. })
  17. if err != nil {
  18. panic(err)
  19. }
  20. c2, err := gfsnotify.Add("/home/john/temp/log", func(event *gfsnotify.Event) {
  21. logger.Debug(ctx, "callback2")
  22. })
  23. if err != nil {
  24. panic(err)
  25. }
  26. // Remove the registration of callback function c1 after 5 seconds, leaving only c2
  27. gtimer.SetTimeout(ctx, 5*time.Second, func(ctx context.Context) {
  28. err = gfsnotify.RemoveCallback(c1.Id)
  29. logger.Debug(ctx, "remove callback c1", err)
  30. })
  31. // Remove the registration of callback function c2 after 10 seconds, all callbacks are removed, and no more log messages are output
  32. gtimer.SetTimeout(ctx, 10*time.Second, func(ctx context.Context) {
  33. err = gfsnotify.RemoveCallback(c2.Id)
  34. logger.Debug(ctx, "remove callback c2", err)
  35. })
  36. select {}
  37. }

Example 2

  1. package main
  2. import (
  3. "context"
  4. "time"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gfsnotify"
  7. "github.com/gogf/gf/v2/os/gtimer"
  8. )
  9. func main() {
  10. var (
  11. ctx = context.Background()
  12. logger = g.Log()
  13. callback = func(event *gfsnotify.Event) {
  14. logger.Debug(ctx, "callback")
  15. }
  16. )
  17. cb, err := gfsnotify.Add("/home/john/temp", callback)
  18. if err != nil {
  19. panic(err)
  20. }
  21. // During this period create files, directories, modify files, delete files
  22. // Remove the callback registration after 20 seconds, all callbacks are removed and no more log messages are output
  23. gtimer.SetTimeout(ctx, 20*time.Second, func(ctx context.Context) {
  24. err = gfsnotify.RemoveCallback(cb.Id)
  25. logger.Debug(ctx, "remove callback", err)
  26. })
  27. select {}
  28. }