首頁 > 後端開發 > Golang > 主體

如何在 Go 中為執行的進程建立等待/忙碌指示器?

Mary-Kate Olsen
發布: 2024-10-25 06:21:02
原創
374 人瀏覽過

How to Create a Waiting/Busy Indicator for Executed Processes in Go?

為執行進程建立等待/忙碌指示器

在Go 中執行子進程時,例如使用exec.Command 安裝npm 套件時,它可能需要很長時間才能看到輸出。為了增強用戶體驗,請考慮顯示一個忙碌指示器來指示過程正在進行中。

解決方案:

一個有效的解決方案包括使用單獨的 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...")

    // Start indicator:
    shutdownCh := make(chan struct{})
    go indicator(shutdownCh)

    err := cmd.Run()

    close(shutdownCh) // Signal indicator() to terminate

    fmt.Println()
    log.Printf("Command finished with error: %v", err)
}</code>
登入後複製

為了獲得更具視覺吸引力的指示器,您可以修改指示器函數以在特定數量的點後列印換行符,例如5:

<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學習者快速成長!