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

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 02:37:30377browse

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

Creating a Waiting/Busy Indicator for Running Processes

When executing a child process like "npm install," it can take significant time for the process to complete and download packages. During this time, it's essential to provide feedback to the user to indicate that the process is ongoing.

Implementing a Busy Indicator

To create a busy indicator, we can leverage another goroutine that runs concurrently with the child process. This goroutine periodically prints a character (e.g., a dot) to the console to show activity. When the child process completes, we signal the goroutine to terminate.

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

Customizing the Indicator

You can modify the indicator to print a new line after a specific number of dots using a modified version of the indicator function:

<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 providing this visual feedback, you can keep users informed that the process is still running and prevent confusion or timeouts caused by the perception of inactivity.

The above is the detailed content of How to Create a Waiting/Busy Indicator for Long-Running 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