Member-only story
How to add time limit to infinite loop in function?
In the development process of Go language, we sometimes need to execute long-running tasks in the background, such as listening or polling certain resources. However, if the task execution time is too long or unexpected situations cause an infinite loop, we usually hope to set a timeout mechanism to terminate the loop. This article will introduce in detail how to set time limits for infinite loops in Go language through an example to ensure the robustness and controllability of the program.
Problem description
We have a Go function for checking RabbitMQ cluster nodes, which contains an infinite loop for continuously executing check commands. The current requirement is to automatically terminate the loop if the function runs for more than 3 minutes.
Original code
The original code is as follows:
func checkRabbitmqClusterIfForgetNode(node string) bool {
for {
cmd := fmt.Sprintf("docker exec -i pam_pam-rabbitmq_1 rabbitmqctl --node %s cluster_status --formatter json", node)
res, err := common.ExecuteCommandWithoutSpace("bash", "-c", cmd)
if err != nil {
log.Errorf("exec cmd %v failed, response: %v error: %v", cmd, res, err)
continue
}
cluster, err := mq.ParseJSON(res)…