cmd_Task.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package utils
  2. import (
  3. "os"
  4. "os/exec"
  5. "strings"
  6. "sync"
  7. )
  8. type RunTask interface {
  9. AddTask()
  10. RunTask()
  11. }
  12. // T: Task任务
  13. type T struct {
  14. sync.Mutex
  15. // ch: 获取时间channel
  16. ch chan struct{}
  17. // 记录pid 用于kill
  18. pid int
  19. // 执行shell命令
  20. exec.Cmd
  21. }
  22. // NewT: 实例化方法
  23. func NewT(path string, args []string, environment ...[]string) *T {
  24. env := os.Environ()
  25. if len(environment) > 0 {
  26. for k, v := range environment[0] {
  27. env[k] = v
  28. }
  29. }
  30. t := &T{
  31. Mutex: sync.Mutex{},
  32. ch: make(chan struct{}),
  33. Cmd: exec.Cmd{
  34. Path: path,
  35. Args: []string{path},
  36. Env: env,
  37. Stdin: os.Stdin,
  38. Stdout: os.Stdout,
  39. Stderr: os.Stderr,
  40. ExtraFiles: make([]*os.File, 0),
  41. },
  42. pid: os.Getpid(),
  43. }
  44. t.Dir, _ = os.Getwd()
  45. if len(args) > 0 {
  46. // Exclude of current binary path.
  47. start := 0
  48. if strings.EqualFold(path, args[0]) {
  49. start = 1
  50. }
  51. t.Args = append(t.Args, args[start:]...)
  52. }
  53. return t
  54. }
  55. func (t *T) AddTask() {
  56. t.Lock()
  57. defer t.Unlock()
  58. if len(t.ch) == 1 {
  59. // 代表已经有任务了
  60. // 直接丢弃这次任务
  61. return
  62. }
  63. t.ch <- struct{}{}
  64. }
  65. func (t *T) RunTask() {
  66. for {
  67. _, ok := <-t.ch
  68. if !ok {
  69. return
  70. }
  71. // todo 执行任务
  72. }
  73. }