Reg Wait time in Go

I need to validate few conditions in my application every 0 to 5 seconds? Can anyone help how to write code for wait for 0 to 5 seconds?


time.Sleep(0 to 5 * time.Second)

1 Like


It depends if you need to run code 0 to 5 seconds after a function is called (it can last some time) or if you need to call a function every 0 to 5 seconds even if last call is not finished to run. What are you looking for ?
If you need strictly to run a validation every 5 seconds however the validation lasts you could need something more elaborated like :

package main

import "time"
import "fmt"

func validate(c1 chan <- string) {
	time.Sleep(2 * time.Second)
	c1 <- "result"

func scheduleValidation (c1 chan <- string) {

	go func () {
		 <-time.After(5 * time.Second)
	} ()

func main() {
		c1 := make(chan string)
		for {
			select {
			case r := <- c1:
1 Like

Thanks Nobbz

Why dont you just use a time.Ticker?

I think that Timer and Ticker are different with regard to an important concern. From the documentation I read about Ticker : β€œIt adjusts the intervals or drops ticks to make up for slow receivers.” That sounds weird, it could drop some ticks. I prefer to assure the regularity unless not needed.

Well, but your implementation might cause overlapping validations, which might be just another bad thing.

Yes and no, it depends how you chunk your validation batch. But yes, you have to be careful.

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