Created
February 2, 2024 13:44
-
-
Save gabriel-samfira/2e059c13d778d00bf2aee8df415131e8 to your computer and use it in GitHub Desktop.
Make an average of newly created files
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 ( | |
"context" | |
"fmt" | |
"log" | |
"os" | |
"os/signal" | |
"path/filepath" | |
"sync/atomic" | |
"syscall" | |
"time" | |
"github.com/fsnotify/fsnotify" | |
) | |
var signals = []os.Signal{ | |
os.Interrupt, | |
syscall.SIGTERM, | |
} | |
func main() { | |
ctx, stop := signal.NotifyContext(context.Background(), signals...) | |
defer stop() | |
// Create new watcher. | |
watcher, err := fsnotify.NewWatcher() | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer watcher.Close() | |
var ops atomic.Uint64 | |
// Start listening for events. | |
go func() { | |
for { | |
select { | |
case event, ok := <-watcher.Events: | |
if !ok { | |
return | |
} | |
if event.Has(fsnotify.Create) { | |
if info, err := os.Stat(event.Name); err != nil { | |
log.Println("error:", err) | |
} else if info.IsDir() { | |
watcher.Add(event.Name) | |
} | |
ops.Add(1) | |
} | |
case err, ok := <-watcher.Errors: | |
if !ok { | |
return | |
} | |
log.Println("error:", err) | |
} | |
} | |
}() | |
go func() { | |
cnt := ops.Load() | |
time.Sleep(5 * time.Second) | |
for { | |
select { | |
case <-ctx.Done(): | |
log.Println("ctx.Done") | |
return | |
default: | |
newCnt := ops.Load() | |
delta := newCnt - cnt | |
var secAvg float64 | |
if delta > 0 { | |
secAvg = float64(float64(delta) / 5) | |
} | |
log.Printf("ops: %d, delta: %d, avg: %.2f\n", newCnt, delta, secAvg) | |
cnt = newCnt | |
time.Sleep(5 * time.Second) | |
} | |
} | |
}() | |
if err := filepath.Walk(os.Args[1], func(path string, info os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} | |
if info.IsDir() { | |
fmt.Printf("add: %s\n", path) | |
watcher.Add(path) | |
} | |
return nil | |
}); err != nil { | |
log.Println("error:", err) | |
} | |
// Add a path. | |
err = watcher.Add(os.Args[1]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Block main goroutine forever. | |
<-ctx.Done() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment