首页 > 后端开发 > Golang > 正文

如何在 Go 中为长时间运行的进程创建等待/忙碌指示器?

Linda Hamilton
发布: 2024-10-25 02:37:30
原创
390 人浏览过

How to Create a Waiting/Busy Indicator for Long-Running Processes in Go?

为正在运行的进程创建等待/忙碌指示器

执行“npm install”等子进程时,可能需要花费大量时间完成和下载软件包的过程。在此期间,必须向用户提供反馈以表明该过程正在进行中。

实现繁忙指示器

要创建繁忙指示器,我们可以利用与子进程同时运行的另一个 goroutine。该 goroutine 定期向控制台打印一个字符(例如,一个点)以显示活动。当子进程完成时,我们通知 goroutine 终止。

<code class="go">func indicator(shutdownCh <-chan struct{}) {
    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()
    for {
        select {
        case <-ticker.C:
            fmt.Print(".")
        case <-shutdownCh:
            return
        }
    }
}

func main() {
    cmd := exec.Command("npm", "install")
    log.Printf("Running command and waiting for it to finish...")

    shutdownCh := make(chan struct{}) // Channel to signal goroutine termination
    go indicator(shutdownCh)

    err := cmd.Run()

    close(shutdownCh) // Signal indicator goroutine to terminate

    fmt.Println()
    log.Printf("Command finished with error: %v", err)
}</code>
登录后复制

自定义指示器

您可以修改指示器以在特定的时间后打印新行使用修改版本的指示器函数的点数:

<code class="go">func indicator(shutdownCh <-chan struct{}) {
    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()
    for i := 0; ; {
        select {
        case <-ticker.C:
            fmt.Print(".")
            if i++; i%5 == 0 {
                fmt.Println()
            }
        case <-shutdownCh:
            return
        }
    }
}</code>
登录后复制

通过提供此视觉反馈,您可以让用户了解进程仍在运行,并防止由于感知不活动而导致混乱或超时。

以上是如何在 Go 中为长时间运行的进程创建等待/忙碌指示器?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!