Home  >  Article  >  Backend Development  >  How to Create a Waiting/Busy Indicator for Executed Processes in Go?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 06:21:02358browse

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

Creating Waiting/Busy Indicator for Executed Process

When executing child processes in Go, such as installing npm packages using exec.Command, it can take a significant amount of time before output is visible. To enhance the user experience, consider displaying a busy indicator to indicate that the process is in progress.

Solution:

One effective solution involves using a separate goroutine to periodically print characters, such as dots, to the console while the process is running. When the process completes, the indicator goroutine can be terminated.

<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>

For a more visually appealing indicator, you can modify the indicator function to print a newline after a specific number of dots, such as 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>

By implementing this solution, you can provide a visual cue to users indicating that a process is executing, enhancing the user experience and making the application more responsive.

The above is the detailed content of How to Create a Waiting/Busy Indicator for Executed Processes in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn