How to perform repeated tasks at a given interval in Go?
Hi everyone! I'm new to Go and writing a small monitoring service. I need the program to check the status of a remote server every 5 seconds and write the result to a log. I tried using `time.Sleep()` in an infinite loop, but it looks hacky and seems to incorrectly block the entire program. Here's my current code:
```go
package main
import (
"fmt"
"time"
)
func main() {
for {
fmt.Println("Checking server...")
// some checking logic here
time.Sleep(5 * time.Second)
}
}
```
The problem is that if I want to stop this loop (for example, by a program termination signal), I'll have to wait for the `Sleep` to finish. Also, I've heard that Go has goroutines and channels, but I don't understand how to apply them for this task.
No answers yet.
Log in to leave an answer
Blogs
Optimizing TypeScript Application Performance: For Beginners
How to Write a REST API in PHP in 30 Minutes: A Step-by-Step Guide for Beginners
Working with WebAssembly and Kotlin: From A to Z
TDD in PHP: How Tests Turn Code into Art