Home > Backend Development > Golang > 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
Release: 2024-10-25 16:36:47
Original
389 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template