Reader small image

You're reading from  Effective Concurrency in Go

Product typeBook
Published inApr 2023
PublisherPackt
ISBN-139781804619070
Edition1st Edition
Concepts
Right arrow
Author (1)
Burak Serdar
Burak Serdar
author image
Burak Serdar

Burak Serdar is a software engineer with over 30 years of experience in designing and developing distributed enterprise applications that scale. He's worked for several start-ups and large corporations, including Thomson and Red Hat, as an engineer and technical lead. He's one of the co-founders of Cloud Privacy Labs where he works on semantic interoperability and privacy technologies for centralized and decentralized systems. Burak holds BSc and MSc degrees in electrical and electronics engineering, and an MSc degree in computer science.
Read more about Burak Serdar

Right arrow

Timers and Tickers

Many long-lived applications impose limits on how long an operation can last. They also perform tasks such as health checks periodically to ensure all components are working as expected. Many platforms provide high-precision timer operations, and the Go standard library provides portable abstractions of these services in the time package. We will look at timers and tickers in this chapter. Timers are tools for doing things later, and tickers are tools for doing things periodically.

The key sections we will review in this chapter are the following:

  • Timer – running something later
  • Tickers – running something periodically

At the end of this chapter, you will have seen how to work with timers and tickers and how you can monitor other goroutines using heartbeats.

Technical Requirements

The source code for this particular chapter is available on GitHub at https://github.com/PacktPublishing/Effective-Concurrency-in-Go/tree/main/chapter7.

Timers – running something later

If you want to do something later, use time.Timer. A Timer is a nice way of doing the following:

// This is only for illustration. Don't do this!
type TimerMockup struct {
     C chan<- time.Time
}
 
func NewTimerMockup(dur time.Duration) *TimerMockup {
     t := &TimerMockup{
          C: make(chan time.Time,1),
     }
     go func() {
          // Sleep, and then send to the channel
          time.Sleep(dur)
          t.C <- time.Now()
          }()
     return t
}

So, a timer is like a goroutine that will send a message to a channel after sleeping for...

Tickers – running something periodically

It may be a reasonable idea to run a function periodically using repeated calls to AfterFunc:

var periodicTask func()
periodicTask = func() {
   DoSomething()
   time.AfterFunc(time.Second, periodicTask)
}
time.AfterFunc(time.Second,periodicTask)

With this approach, each run of the function will schedule the next one, but variations in the running duration of the function will accumulate over time. This may be perfectly acceptable for your use case, but there is a better and easier way to do this: use time.Ticker.

time.Ticker has an API very similar to that of time.Timer: You can create a ticker using time.NewTicker, and then listen to a channel that will periodically deliver a tick until it is explicitly stopped. The period of the tick will not change based on the running time of the listener. The following program prints the number of milliseconds elapsed since the beginning of the program for...

Summary

Timers and tickers allow you to do things in the future and do things periodically. We only looked at a few use cases here. They are versatile tools that show up quite often in unexpected places. The Go runtime provides extremely efficient implementations of these tools. You need to be careful, though because they invariably complicate the flow. Make sure to close your tickers.

In the remaining chapters, we will start putting things together and look at some real-life use cases for concurrency patterns.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Effective Concurrency in Go
Published in: Apr 2023Publisher: PacktISBN-13: 9781804619070
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Burak Serdar

Burak Serdar is a software engineer with over 30 years of experience in designing and developing distributed enterprise applications that scale. He's worked for several start-ups and large corporations, including Thomson and Red Hat, as an engineer and technical lead. He's one of the co-founders of Cloud Privacy Labs where he works on semantic interoperability and privacy technologies for centralized and decentralized systems. Burak holds BSc and MSc degrees in electrical and electronics engineering, and an MSc degree in computer science.
Read more about Burak Serdar