Go Package time: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 43: Line 43:
=<tt>Ticker</tt>=
=<tt>Ticker</tt>=
==<tt>NewTicker()</tt>==
==<tt>NewTicker()</tt>==
<code>NewTicker()</code> returns a new <code>[[#Ticker|Ticker]]</code> containing a channel that will send the current time on the channel after each tick. The period of the ticks is specified by the duration argument. The ticker will adjust the time interval or drop ticks to make up for slow receivers. Stop the ticker to release associated resources.


==<tt>Tick</tt>==
==<tt>Tick</tt>==

Revision as of 19:30, 13 February 2024

External

Internal

Overview

  • time.After returns a channel that after the given duration, will send current time on it. This can be used to implement a timeout with select.

time.Sleep()

https://golang.org/pkg/time/#Sleep

Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately:

import "time"
...
secs := 10
time.Sleep(time.Duration(secs) * time.Second)

Other available time units: time.Milliseconds.

time.Now()

Return the current local time as an instance of a Time struct.

time.Since()

Time

A time structure that represents an instant in time with nanosecond precision.

sec()

Return seconds since Jan 1 year 1.

UnixNano()

Return the number of nanoseconds elapsed since January 1, 1970 UTC, represented on 8 bytes (int64). The result does not depend on the location associated with the time instance the method was called on.

After(Duration)

The After() returns a channel that will provide a Time instance after the given duration elapses. Equivalent with NewTimer(d).C.

The function can be used with a select statement to time out the select statement if none of the participating channels ever unblock. It does that by returning a channel what will send the current time after the provided duration.

Duration

Ticker

NewTicker()

NewTicker() returns a new Ticker containing a channel that will send the current time on the channel after each tick. The period of the ticks is specified by the duration argument. The ticker will adjust the time interval or drop ticks to make up for slow receivers. Stop the ticker to release associated resources.

Tick

Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks". Unlike NewTicker, Tick will return nil if d <= 0.

Idioms

A Clock that Does Something Every Second

for range time.Tick(1 * time.Second) {
  fmt.Printf(".\n")
}