DEV Community

Ankit malik
Ankit malik

Posted on

Go: Ticker vs Timer

Introduction

Go or Golang is a powerful language that offers several features to simplify the development of concurrent and networked programs. One of these features is the ability to schedule tasks to run at specific times or intervals. This functionality is provided by two types of timers in Golang: time.Timer and time.Ticker.

Both of these are useful for scheduling tasks, but they have different use cases and behaviours. In this article, we'll explore the differences between the two and when to choose which one.

Golang Timer

The time.Timer type represents a single event that will occur in the future only once. When a timer is created, it does not start automatically. Instead, it waits for a specified duration and then fires once. Once the timer has fired, it cannot be used again.

Let's look at an example of how to create a timer that fires after a 2-second delay:

package main

import (
    "fmt"
    "time"
)

func main() {
    timer := time.NewTimer(2 * time.Second)

    <-timer.C
    fmt.Println("Timer fired!")
}

Enter fullscreen mode Exit fullscreen mode

Playground URL: https://go.dev/play/p/FFC-f9IdygK

In this example, we create a new timer using the time.NewTimer function and pass it a duration of 2 second. We then wait for the timer to fire by reading from its C channel using the <- operator. Once the timer has fired, we print a message to the console.

It's important to note that if we try to reset the timer after it has fired, we'll get a panic:

timer.Reset(time.Second) // panic: Reset called on a Timer that has already fired or been stopped

Enter fullscreen mode Exit fullscreen mode

Golang Ticker

The time.Ticker type represents a recurring event that fires at a fixed interval. When a ticker is created, it starts automatically and fires at the specified interval until stopped. Unlike the time.Timer, a ticker can be reset and reused means we can change the duration for which it will be fired.

Lets look at an example of how to create a ticker that fires every 500 milliseconds:

package main

import (
    "fmt"
    "time"
)

func main() {
    ticker := time.NewTicker(500 * time.Millisecond)

    go func() {
        for t := range ticker.C {
            fmt.Println("Tick at", t)
        }
    }()

    time.Sleep(2000 * time.Millisecond)
    ticker.Stop()
    fmt.Println("Ticker stopped")
}

Enter fullscreen mode Exit fullscreen mode

Playground URL: https://go.dev/play/p/b9GoglOKTHj

In this example, we create a new ticker using the time.NewTicker function and pass it an interval of 500 milliseconds. We then create a goroutine that loops over the ticker's C channel, printing the current time each time the ticker fires. We let the ticker run for 2 seconds before calling its Stop method to halt the ticker's firing.

It's important to note that if we try to reset a stopped ticker, we'll get a panic:

ticker.Stop()
ticker.Reset(1000 * time.Millisecond) // panic: Reset called on a stopped Ticker

Enter fullscreen mode Exit fullscreen mode

Use Cases

So, when should we use a timer versus a ticker? Here are a few examples:

Timer

  • A timer is useful when you need to perform a task once after a specific duration has elapsed.
  • A timer is also useful when you want to ensure that a task is executed at a specific time in the future.

Ticker

  • A ticker is useful when you need to perform a task repeatedly at a fixed interval.
  • A ticker is also useful when you want to periodically check the status of something, such as a connection to a server.
  • A ticker is also useful when you want to update cache at specific interval.

Conclusion

In conclusion, the time.Timer and time.Ticker types in Golang provide powerful functionality for scheduling tasks. Timer are for firing at an event only once and Ticker is for firing the event continuously.

Oldest comments (0)