miket
(Mike)
May 26, 2021, 1:23pm
1
Hello - total noob question. Why do I only get the “Failed to ping…” message written to the console when running the below?
func main() {
url := "abc.com"
timeout := time.Second * 3
pingTicker := time.NewTicker(30 * time.Second)
for {
select {
case <-pingTicker.C:
success := ping(url, timeout)
if !success {
pingTicker.Stop()
fmt.Println("Failed to ping...")
return
}
}
}
fmt.Println("Process terminated")
}
nyggus
(Nyggus)
May 26, 2021, 1:53pm
2
Hello. Note that after the process executes the line you mentioned (fmt.Println("Failed to ping...")
), it returns from the function (the next line is return
), so it means the main()
function ends — so nothing else will be executed.
luk4z7
(Lucas Alves)
May 26, 2021, 2:05pm
3
Yep, and if you need scape from the “for” you need this, otherwise you will get an error, or in some cases, you will wait forever “for”
Failed to ping…
fatal error: all goroutines are asleep - deadlock!
package main
import (
"fmt"
"time"
)
func main() {
url := "abc.com"
timeout := time.Second * 3
pingTicker := time.NewTicker(1 * time.Second)
loop:
for {
select {
case <-pingTicker.C:
success := ping(url, timeout)
if !success {
pingTicker.Stop()
fmt.Println("Failed to ping...")
break loop
}
}
}
fmt.Println("Process terminated")
}
func ping(u string, t time.Duration) bool {
return false
}
miket
(Mike)
May 26, 2021, 3:25pm
4
Thank you both! I feel stupid - for some reason I thought the return statement in the for loop had a different meaning.
system
(system)
Closed
August 24, 2021, 3:25pm
5
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.