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!