What does this code do?

There is a pice of code from server shutdown function. I guess it implements a gracefull shutdown and it waits for unfinished background jobs and waits for amount of time to finish it. If time exceed it shutdowns anyway.

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = srv.Shutdown(ctx)

Is it right?

I made a dummy handler which makes long database call which is actualy smaller than 10 seconds, but anyway if I stop the server when that database call is still processing then that handler had no chance to finish because the above code finished before - i.e. server stoped earlier.

So what is sence of that time amount in the context.WithTimeout(…) function?

2 Likes

The code you posted cancels the context after 10 seconds, but it’s up to the implementation of srv.Shutdown to check that context to see if a cancellation is requested and act accordingly.

Contexts by themselves do not abort/break/cancel any operations; it’s up to the code that receives a context to observe that context and abort/break/cancel.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.