MST

星途 面试题库

面试题:Go语言中time包定时器的基础使用

请用Go语言的time包实现一个简单的定时器,每2秒打印一次'Hello, Timer!',并在10秒后停止定时器。
25.3万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
    "time"
)

func main() {
    timer := time.NewTimer(2 * time.Second)
    stop := make(chan struct{})

    go func() {
        for {
            select {
            case <-timer.C:
                fmt.Println("Hello, Timer!")
                timer.Reset(2 * time.Second)
            case <-time.After(10 * time.Second):
                timer.Stop()
                close(stop)
                return
            }
        }
    }()

    <-stop
}