spread_writer.go 783 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package writers
  2. import (
  3. "io"
  4. "time"
  5. )
  6. type SpreadWriter struct {
  7. w io.Writer
  8. interval time.Duration
  9. buf [][]byte
  10. exitCh chan int
  11. }
  12. func NewSpreadWriter(w io.Writer, interval time.Duration, exitCh chan int) *SpreadWriter {
  13. return &SpreadWriter{
  14. w: w,
  15. interval: interval,
  16. buf: make([][]byte, 0),
  17. exitCh: exitCh,
  18. }
  19. }
  20. func (s *SpreadWriter) Write(p []byte) (int, error) {
  21. b := make([]byte, len(p))
  22. copy(b, p)
  23. s.buf = append(s.buf, b)
  24. return len(p), nil
  25. }
  26. func (s *SpreadWriter) Flush() {
  27. sleep := s.interval / time.Duration(len(s.buf))
  28. ticker := time.NewTicker(sleep)
  29. for _, b := range s.buf {
  30. s.w.Write(b)
  31. select {
  32. case <-ticker.C:
  33. case <-s.exitCh: // skip sleeps finish writes
  34. }
  35. }
  36. ticker.Stop()
  37. s.buf = s.buf[:0]
  38. }