另客网go项目公用的代码库

12345678910111213141516171819202122232425262728293031323334
  1. package timeout
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. type executeChan struct {
  7. c chan bool
  8. once sync.Once
  9. }
  10. //Run 返回函数f是否被运行
  11. func Run(limit time.Duration, f func()) bool {
  12. ec := &executeChan{c: make(chan bool), once: sync.Once{}}
  13. whether := true
  14. go func() {
  15. f()
  16. ec.once.Do(func() {
  17. ec.c <- true
  18. close(ec.c)
  19. })
  20. }()
  21. select {
  22. case <-time.After(limit):
  23. whether = false
  24. case <-ec.c:
  25. }
  26. return whether
  27. }