Home  >  Article  >  Backend Development  >  How to create busy indicators for long-running processes in Go using goroutines?

How to create busy indicators for long-running processes in Go using goroutines?

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 16:36:47284browse

How to create busy indicators for long-running processes in Go using goroutines?

Creating Busy Indicators for Executed Processes

When executing child processes that take an extended duration, it's crucial to provide users with a way to know that the process is indeed running. Without an indicator, users may remain unaware of the progress or even think that the system has become unresponsive.

To address this issue, various busy indicators can be implemented to provide visual cues to the user. One such indicator involves periodically printing a character, such as a dot or a progress bar, to the console.

Using Goroutines for Busy Indicators

Goroutines are lightweight threads in the Go programming language, which can be utilized to create a separate thread responsible for managing the busy indicator. Here's how this can be accomplished:

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

In this example, a goroutine named indicator() is created that periodically prints a dot to the console. The goroutine continues printing until a signal is received from the shutdownCh channel. When the child process completes, the main goroutine closes shutdownCh, causing the indicator() goroutine to terminate and stop printing dots.

Customizing Busy Indicators

The busy indicator can be further customized by adjusting the rate at which it prints or by adding different characters or patterns. For example, to print a dot every second and a new line after every 5 dots, the indicator() function can be modified as follows:

<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 incorporating a busy indicator in your application, you can provide users with a more responsive and user-friendly experience, assuring them that their process is executing in the background while they wait for the results.

The above is the detailed content of How to create busy indicators for long-running processes in Go using goroutines?. 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