Timer and Callback Functions in Golang
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