» Quick Introduction to Go » 3. Advanced » 3.3 Time

Time

Package time provides functionality for measuring and displaying time.

Time

A Time represents an instant in time with nanosecond precision.

package main

import (
	"fmt"
	"time"
)

func main() {
	// Get the current time
	currentTime := time.Now()

	// Format and display the time
	fmt.Println("Current Time:", currentTime.Format("2006-01-02 15:04:05"))

    t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
	fmt.Printf("Go launched at %s\n", t.Local())
}

Epoch

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch (00:00:00 UTC on 1 January 1970).

package main

import (
	"fmt"
	"time"
)

func main() {
	currentTime := time.Now()
	epochTime := currentTime.Unix()
	fmt.Println("Current Epoch Time:", epochTime)
}

Timeouts

In Go, the time.After function can be used to create a channel that sends the current time after a specified duration. It is often used for implementing timeouts.

package main

import (
	"fmt"
	"time"
)

func main() {
	timeoutDuration := 3 * time.Second

	// Create a channel that will receive the current time after the specified duration
	timeoutChan := time.After(timeoutDuration)

	fmt.Println("Start operation...")

	time.Sleep(2 * time.Second)

	select {
	case <-timeoutChan:
		fmt.Println("Operation timed out!")
	case <-time.After(time.Second):
		fmt.Println("Operation completed successfully.")
	}
}

Timers

It provides a Timer type that can be used to perform an action after a specified amount of time.

package main

import (
	"fmt"
	"time"
)

func main() {
	timeoutDuration := 3 * time.Second

	// Create a Timer that will fire after the specified duration
	timer := time.NewTimer(timeoutDuration)

	fmt.Println("Start operation...")

	time.Sleep(2 * time.Second)

	// Wait for the timer to expire
	<-timer.C

	fmt.Println("Operation timed out!")
}

Tickers

The Ticker type that can be used to perform an action at regular intervals.

package main

import (
	"fmt"
	"time"
)

func main() {
	// Create a ticker that ticks every 1 second
	ticker := time.NewTicker(1 * time.Second)

	fmt.Println("Start operation...")

	for i := 0; i < 5; i++ {
		<-ticker.C

		// Perform the action at each tick
		fmt.Println("Tick", i)
	}

	ticker.Stop()

	fmt.Println("Operation completed successfully.")
}
// => Start operation...
// Tick 0
// Tick 1
// Tick 2
// Tick 3
// Tick 4
// Operation completed successfully.

Rate Limiting

Rate limiting is an important mechanism for controlling resource utilization and maintaining quality of service.

Go provides a package called golang.org/x/time/rate that makes it easy to implement rate limiting. Or, you can manually use the time.Ticker to achieve rate limiting.

package main

import (
    "fmt"
    "time"
)

func main() {

    requests := make(chan int, 5)
    for i := 1; i <= 5; i++ {
        requests <- i
    }
    close(requests)

    limiter := time.Tick(200 * time.Millisecond)

    for req := range requests {
        <-limiter
        fmt.Println("request", req, time.Now())
    }
}
// => 
// request 1 2013-10-07 16:41:15.236641687 +0000 UTC m=+0.200585747
// request 2 2013-10-07 16:41:15.436968762 +0000 UTC m=+0.400912897
// request 3 2013-10-07 16:41:15.636203458 +0000 UTC m=+0.600147531
// request 4 2013-10-07 16:41:15.836366439 +0000 UTC m=+0.800310502
// request 5 2013-10-07 16:41:16.036687838 +0000 UTC m=+1.000631919

Code Challenge

Create a program that periodically performs a task at a specified interval.

Loading...
> code result goes here
Prev
Next