Timers in Go

Go: Timers

Timers can be created using the time package. it allow you to schedule a function to be called after a certain amount of time has passed.

Here's an example:


    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        // create a timer that will expire after 2 seconds
        timer := time.NewTimer(2 * time.Second)

        fmt.Println("Waiting for timer to expire...")

        // block until the timer expires
        <-timer.C

        fmt.Println("Timer expired!")
    }

In this example, we create a new timer that will expire after 2 seconds using the NewTimer function. We then wait for the timer to expire by blocking on the timer's C channel.

When the timer expires, the C channel is closed and the blocking operation on <-timer.C is unblocked. We then print out a message indicating that the timer has expired.

If you want to stop a timer before it expires, you can call the Stop method on the timer. Here's an example:


    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        // create a timer that will expire after 5 seconds
        timer := time.NewTimer(5 * time.Second)

        fmt.Println("Waiting for timer to expire...")

        // stop the timer before it expires
        stopped := timer.Stop()

        if stopped {
            fmt.Println("Timer stopped before it could expire!")
        } else {
            fmt.Println("Timer expired before it could be stopped!")
        }
    }

In this example, we create a new timer that will expire after 5 seconds using the NewTimer function. We then immediately stop the timer using the Stop method. We check the return value of Stop to determine if the timer was stopped before it could expire or if it had already expired.

I hope this helps you understand how to use timers in Go! Let me know if you have any other questions.

Previous Article

Next Article