Timer and Callback Functions in Golang

Prince Pereira
1 min readMay 19, 2021

--

Implement a timer based callback func in Golang

Program

package mainimport (
"fmt"
"sync"
"time"
)
type timerFunc func()var timers *sync.Mapfunc startTimer(id string, callbackFunc timerFunc, timeout int) {
if a, ok := timers.Load(id); ok {
timer := a.(*time.Timer)
timer.Stop()
timers.Delete(id)
// Delete from DB
fmt.Println("=========== Existing Timer deleted ...", id)
}
timer := time.NewTimer(time.Duration(timeout) * time.Second)
fmt.Println("=========== Timer started ...", id)
timers.Store(id, timer)
// Add in DB
go func() {
<-timer.C
fmt.Println("=========== Callback func calling ...", id)
callbackFunc()
fmt.Println("=========== Timer completed...", id)
timers.Delete(id)
}()
}
func stopTimer(id string) {
if a, ok := timers.Load(id); ok {
timer := a.(*time.Timer)
timer.Stop()
timers.Delete(id)
// Delete from DB
fmt.Println("=========== Timer deleted...", id)
}
}
func a() {
fmt.Println("=========== a called...")
}
func b() {
fmt.Println("=========== b called...")
}
func main() {
timers = new(sync.Map)
fmt.Println("=========== Execution started")
startTimer("id-a", a, 2)
startTimer("id-b", b, 4)
time.Sleep(8 * time.Second)
startTimer("id-a", a, 4)
startTimer("id-b", b, 4)
time.Sleep(2 * time.Second)
stopTimer("id-a")
time.Sleep(100 * time.Second)
fmt.Println("=========== Execution completed")
}

Output

===========  Execution started
=========== Timer started ... id-a
=========== Timer started ... id-b
=========== Callback func calling ... id-a
=========== a called...
=========== Timer completed... id-a
=========== Callback func calling ... id-b
=========== b called...
=========== Timer completed... id-b
=========== Timer started ... id-a
=========== Timer started ... id-b
=========== Timer deleted... id-a
=========== Callback func calling ... id-b
=========== b called...
=========== Timer completed... id-b
=========== Execution completed

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Prince Pereira
Prince Pereira

Written by Prince Pereira

Senior Software Engineer - Microsoft | SDN | Java | Golang | DS & Algo | Microservices | Kubernetes | Docker | gRPC & Protocol Buffer

No responses yet

Write a response