task.go 568 B

1234567891011121314151617181920212223242526272829303132333435
  1. package workpool
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. // Task interface
  7. type Task interface {
  8. Run() *[]byte
  9. }
  10. // FutureTask out must be blocking chan (size=0)
  11. type FutureTask struct {
  12. T Task
  13. out chan *[]byte
  14. }
  15. // NewFutureTask .
  16. func NewFutureTask(t Task) *FutureTask {
  17. return &FutureTask{
  18. T: t,
  19. out: make(chan *[]byte, 1),
  20. }
  21. }
  22. // Wait for task return until timeout
  23. func (ft *FutureTask) Wait(timeout time.Duration) (res *[]byte, err error) {
  24. select {
  25. case res = <-ft.out:
  26. case <-time.After(timeout):
  27. err = fmt.Errorf("task(%+v) timeout", ft)
  28. }
  29. return
  30. }