task.go 760 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package task
  2. import (
  3. "context"
  4. "gd_adm_data/errors"
  5. "fmt"
  6. "time"
  7. "gd_adm_data/common.in/utils"
  8. )
  9. type Task func() error
  10. func Do(ctx context.Context, tasks ...Task) (returnErr error) {
  11. utils.GC()
  12. if utils.ExitRecieved == true {
  13. return errors.SystemError
  14. }
  15. // 开始时间
  16. startTime := uint64(time.Now().UnixNano())
  17. // 抓异常代码
  18. defer func() {
  19. status := "SUCCESS"
  20. if r := recover(); r != nil {
  21. if e, ok := r.(error); ok {
  22. returnErr = e
  23. } else {
  24. returnErr = fmt.Errorf("%+v", r)
  25. }
  26. }
  27. if returnErr != nil {
  28. status = "FAIL"
  29. }
  30. printAccessLog(ctx, startTime, status)
  31. }()
  32. for _, task := range tasks {
  33. if task != nil {
  34. if err := task(); err != nil {
  35. returnErr = err
  36. return
  37. }
  38. }
  39. }
  40. return
  41. }