从非Chan类型的时间接收。

In this tutorial is following example provided:

func LongRunningHandler(ctx context.Context) string {
        deadline, _ := ctx.Deadline()
        for {
                select {
                case <- time.Until(deadline).Truncate(100 * time.Millisecond):
                        return "Finished before timing out."
                default:
                        log.Print("hello!")
                        time.Sleep(50 * time.Millisecond)
                }
        }
}

When I compile this code I get following error: invalid operation: <-time.Until(deadline).Truncate(100 * time.Millisecond) (receive from non-chan type time.Duration)

What is wrong with the code from the example?

<- is for receiving from a Channel, for this neither time.Until or Truncate returns a channel.

In this case the error message is identifying the issue, but doesn't really tell what actually to do differently.

go DOES provide some time methods that do return channels. One of which is time.After

select {
case m := <-c:
        handle(m)
case <-time.After(5 * time.Minute):
        fmt.Println("timed out")
}

I would highly recommend go by example and a tour of go. They do an amazing job introducing channels and for/select

Use time.After

func LongRunningHandler(ctx context.Context) string {
        deadline, _ := ctx.Deadline()
        for {
                select {
                case <- time.After(time.Until(deadline).Truncate(100 * time.Millisecond)):
                        return "Finished before timing out."
                default:
                        log.Print("hello!")
                        time.Sleep(50 * time.Millisecond)
                }
        }
}