dozc58418381 2016-06-23 13:10
浏览 75
已采纳

Golang检索应用程序正常运行时间

I'm trying to retrieve the current uptime of my Go application.

I've seen there's a package syscall which provides a type Sysinfo_t and a method Sysinfo(*Sysinfo_t) which apparently allows you to retrieve the Uptime (since it's a field of the Sysinfo_t struct)

What I've done so far is:

sysi := &syscall.Sysinfo_t{}

if err := syscall.Sysinfo(sysi); err != nil {
    return http.StatusInternalServerError, nil
}

The problem is that at compile time I get this:

/path/to/file/res_system.go:43: undefined: syscall.Sysinfo_t
/path/to/file/res_system.go:45: undefined: syscall.Sysinfo

I've searched a bit and apparently that method and type are available only on Linux and I need the application to run both on Linux and OsX (which I'm currently using).

Is there a cross-compatible way to retrieve the application uptime?

NOTE: I'd rather not use any third party libraries (unless they're absolutely necessary)

  • 写回答

3条回答 默认 最新

  • doutan5844 2016-06-23 15:23
    关注

    Simple way to get uptime is to store service start time:

    https://play.golang.org/p/by_nkvhzqD

    package main
    
    import (
        "fmt"
        "time"
    )
    
    var startTime time.Time
    
    func uptime() time.Duration {
        return time.Since(startTime)
    }
    
    func init() {
        startTime = time.Now()
    }
    
    func main() {
        fmt.Println("started")
    
        time.Sleep(time.Second * 1)
        fmt.Printf("uptime %s
    ", uptime())
    
        time.Sleep(time.Second * 5)
        fmt.Printf("uptime %s
    ", uptime())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab