[go] Execute function by timer

Can you please tell me if there are standard methods in go to start functions on a timer, for example, is it possible to specify a function to execute every 3 seconds?

You can use select

package main

import (
	"fmt"
	"time"
)

func main() {
	for {
		select {
		case <-time.After(time.Second * 3):
			fmt.Println("Hello, playground")
		}
	}
}

https://play.golang.org/p/lKpu8lcaFQq

2 Likes

thank you, but how to make the code run in the background? Because the compiler shows that the code after the for loop will never be executed.

Make it run in its own go routine

1 Like

Yes all works =) thanks all

1 Like

Another method is using time.Tick

for range time.Tick(time.Second * 3) {
	println("ping!")
}

https://play.golang.org/p/KN6RAIjRC0H

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.