apm_heartbeat.go 770 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package containers
  2. import (
  3. log "github.com/sirupsen/logrus"
  4. "os"
  5. "strconv"
  6. "time"
  7. )
  8. var hbStopChan = make(chan struct{})
  9. func DoHeartbeat(hbFilePath string) {
  10. defer func() {
  11. if err := recover(); err != nil {
  12. log.Errorf("DoHeartbeat panic: %v", err)
  13. }
  14. }()
  15. doHeartbeat(hbFilePath)
  16. ticker := time.NewTicker(time.Second * 30)
  17. for {
  18. select {
  19. case <-ticker.C:
  20. doHeartbeat(hbFilePath)
  21. case <-hbStopChan:
  22. return
  23. }
  24. }
  25. }
  26. func doHeartbeat(hbFilePath string) {
  27. timeUnix := time.Now().Unix()
  28. timeStr := strconv.FormatInt(timeUnix, 10)
  29. if err := os.WriteFile(hbFilePath, []byte(timeStr), 0644); err != nil {
  30. log.Errorf("write heartbeat to file [%s] occurs error: %v", hbFilePath, err.Error())
  31. }
  32. }
  33. func StopHeartbeat() {
  34. close(hbStopChan)
  35. }