timeutils.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package timeutils2
  15. import (
  16. "fmt"
  17. "runtime/debug"
  18. "time"
  19. "yunion.io/x/log"
  20. "yunion.io/x/onecloud/pkg/util/procutils"
  21. )
  22. func AddTimeout(second time.Duration, callback func()) {
  23. go func() {
  24. defer func() {
  25. if r := recover(); r != nil {
  26. log.Errorln(r)
  27. debug.PrintStack()
  28. }
  29. }()
  30. <-time.NewTimer(second).C
  31. callback()
  32. }()
  33. }
  34. func CommandWithTimeout(timeout int, cmds ...string) *procutils.Command {
  35. if timeout > 0 {
  36. cmds = append([]string{"timeout", "--signal=KILL", fmt.Sprintf("%ds", timeout)}, cmds...)
  37. }
  38. return procutils.NewCommand(cmds[0], cmds[1:]...)
  39. }