Creating a Waiting/Busy Indicator for Executed Processes
When executing child processes, like in the example provided, it can be beneficial to provide visual feedback to the user indicating that the process is running, especially when the execution time can be lengthy. This can help prevent the user from thinking the program has frozen.
To create a waiting/busy indicator, one approach is to utilize a goroutine to print something periodically while the process is executing. When the process completes, a signal can be sent to the goroutine to terminate it.
Here's a code sample that demonstrates this approach:
<code class="go">package main import ( "fmt" "log" "os/exec" "time" ) 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>
This code uses a ticker to print a dot every second and a shutdown channel to signal the indicator goroutine to terminate when the process finishes.
To start a new line after every five dots, modify the indicator function 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 implementing this type of indicator, you can provide clear visual feedback to users, indicating that the process is running and has not frozen.
The above is the detailed content of How can I create a visually appealing waiting/busy indicator for long-running processes in Go?. For more information, please follow other related articles on the PHP Chinese website!