The best way to do this is to plumb a context.Context
<https://pkg.go.dev/context#Context> through all long-running functions -
in particular, anything talking to the network.
Most RPC and network frameworks provide a way to pass a Context, so
consistently doing this will more or less transparently cancel your
business logic ASAP.
For purely CPU bound code, this is a bit more awkward, because you indeed
have to intersperse code like
select {
    case <-ctx.Done():
        return ctx.Err()
    default:
}
to make the code return early. But that should be relatively rare.

On Tue, Jan 11, 2022 at 8:53 PM E Z <legend...@gmail.com> wrote:

> I'm using golang to implement a task schedule and process system.
>
> I found that golang can't stop the goroutine externally,  we must wait for
> the goroutine to end itself. I can stop a goroutine through a channel,
> however, the only time to check the value of the channel is when the select
> is called, and this must wait until the execution of the business function
> ends, which can take a long time.
>
> for example:
>
> ticker := time.NewTicker(task.period)
> defer ticker.Stop()
> for {
>     select {
>         case <-task.channel:
>             return
>         case <-ticker.C:
>             _ =  task.task.Run(task.logger)
>      }
> }
>
> The above code is executing in a goroutine, if I want to cancel this
> goroutine, I can send a signal to task.channel, but the signal only can be
> retrieved after the task.task.Run is finished, it may be a long time, such
> as 5 mins.
>
> Is there any good idea to cancel the goroutine like the above code as soon
> as possible?
>
> Thanks,
> Ethan
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/72dcd177-028e-43a3-aff9-6a6258e29bc4n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/72dcd177-028e-43a3-aff9-6a6258e29bc4n%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAEkBMfGqwfRu7MA5mqytW2JKdX6R1ZBE3_7REHQAh%2Bc_jDvaNA%40mail.gmail.com.

Reply via email to