Golang: How to use Ticker and Timer

SHIVAM SOURAV JHA
3 min readAug 18, 2024

--

Deployment platforms like Render have an issue, in the free instance they spin down with inactivity, which can delay requests by 50 seconds or more.
To keep your application running always you can do make a work around.

Ticker and Timer are some packages in Golang can help us keep our application running forever. Let’s discuss in details what can be use

But what is Ticker?

Ticker is a mechanism provided by time package. It sends a signal via a channel on a regular interval. Now how can we benefit from this?

We can put a ticker and after a gap of every 30 seconds hit on a endpoint of our application.

How to intialise a ticker?

Like other data structures in Golang, ticker is also initialised via a simple definition.

    ticker := time.NewTicker(500 * time.Millisecond)

But how to write the code for this? To write the code we must know our requirements:-
1. We want our application to be running in background independently: what’s better than Goroutines?

2. We want our application to keep running forever in the background: What’s better than never ending For loop?

So our solution looks something like this

 go func() {
for {

}
}()

Our next requirement is to keep calling it after a regular interval

 go func() {
for {
select {
case t := <-ticker.C:
//code to call the webhook
}
}
}()

If used in main function, the above code snippet looks like:

func main() {
go func() {
for {
select {
case t := <-ticker.C:
//code to call the webhook
}
}
}()

routes := gin.New()
handlers := routes.Group("api")
{
handlers.POST("/cat", cat)
}
port := "8081"
err := routes.Run(":" + port)
if err != nil {
fmt.Println(err.Error())
}
}

Thus by doing this we can keep running our application after every 30 seconds.

Using stopper

When you’re done using the Ticker, it's important to stop it by calling Ticker.Stop() to release the resources associated with it.

How would Ticker work

After every 30 seconds ticker would send a signal via a channel and our application would call a webhook of the same application, resulting in our application never going down.

What is Timer?

Timer is yet another offering by time package. It is however different from Ticker, because unlike Ticker, timer would be called after a certain duration.

Like a ticker, a timer has a channel (C) that sends the current time after the specified duration has passed. And unlike a ticker, a timer only fires once. Once the specified time duration has elapsed, the timer sends a signal on its channel and stops.

How would timer code work?

func main() {
// Initialize a new timer with a 30-second duration
timer := time.NewTimer(30 * time.Second)

// Start a goroutine to handle the timer's execution
go func() {
for {
<-timer.C // Wait for the timer to fire
callWebhook() // Call the webhook

// Reset the timer to fire again after 30 seconds
timer.Reset(30 * time.Second)
}
}()

// Setup routes using Gin (as per your example)
routes := gin.New()
handlers := routes.Group("api")
{
handlers.POST("/cat", func(c *gin.Context) {
// Example handler function for the /cat endpoint
c.JSON(200, gin.H{"message": "cat endpoint hit"})
})
}

port := "8081"
err := routes.Run(":" + port)
if err != nil {
fmt.Println(err.Error())
}
}

What is happening?

After every 30 seconds we reset the counter and wait for next 30 seconds in background for an event. Once that event is achieved we call the webhook to hit the application, preventing application from going down.

So these two approaches seemed like a good way of ensuring our server from going down.

--

--