Golang : Call a function after some delay(time.Sleep and Tick)
Long time ago when I started learning Turbo Pascal by myself. One of the few functions that I'd learned is the delay()
function. Ah... those days..very nostalgic.
Anyway, these programs below will show you how to call a function after some delay. First example uses the time.Sleep()
function and the second example uses the time.Tick()
function.
Example 1:
package main
import (
"fmt"
"time"
)
func delaySecond(n time.Duration) {
time.Sleep(n * time.Second)
}
func delayMinute(n time.Duration) {
time.Sleep(n * time.Minute)
}
func main() {
fmt.Println("starts")
delaySecond(3) // delay 3 seconds
fmt.Println("after 3 second")
delayMinute(1) // delay 1 minute
fmt.Println("after 1 minute delay... now get back to work!")
}
Example 2 - For polling after 5 seconds
package main
import (
"fmt"
"time"
)
func echo(s string) {
fmt.Println(s)
}
func delaySecond(n time.Duration) {
for _ = range time.Tick(n * time.Second) {
str := "Hi! " + n.String() + " seconds have passed"
echo(str)
}
}
func main() {
go delaySecond(5) // very useful for interval polling
select {} // this will cause the program to run forever
}
The reason second example used the time.Tick()
function is because time.Sleep()
function will cause this error :
fatal error: all goroutines are asleep - deadlock!
Output : see http://play.golang.org/p/W3EYOHA-YS
Reference :
https://groups.google.com/forum/#!topic/golang-nuts/W1KJQr35NE0
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.2k Golang : Generate DSA private, public key and PEM files example
+8.6k Golang : Populate or initialize struct with values example
+8k Swift : Convert (cast) Character to Integer?
+7.5k Golang : Scan files for certain pattern and rename part of the files
+5.4k Swift : Get substring with rangeOfString() function example
+15.8k Golang : Get sub string example
+11.3k Golang : Change date format to yyyy-mm-dd
+18.8k Golang : Get host name or domain name from IP address
+8.3k Golang : Another camera capture GUI application with GTK and OpenCV
+9.1k Golang : Create unique title slugs example
+8.8k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+9.7k Golang : Translate language with language package example