go / expert
Snippet
Asynchronous Task Orchestration via Context AfterFunc Registration
Go 1.21 introduced context.AfterFunc, which schedules a closure to run in its own goroutine after a context is cancelled. Calling the returned stopFunc unregisters the handler. If stopFunc returns true, it confirms that the callback was prevented from running, enabling deterministic resource cleanup and race-free termination coordination.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package mainimport ("context""fmt""sync""time")func executeOrchestratedTask(ctx context.Context) error {var wg sync.WaitGroupwg.Add(1)stopFunc := context.AfterFunc(ctx, func() {fmt.Println("Context cancelled: Aborting background worker...")wg.Done()})go func() {defer wg.Done()select {case <-time.After(100 * time.Millisecond):if stopFunc() {fmt.Println("Task completed successfully before context deadline.")}case <-ctx.Done():return}}()wg.Wait()return ctx.Err()}func main() {ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)defer cancel()_ = executeOrchestratedTask(ctx)}
Breakdown
1
stopFunc := context.AfterFunc(ctx, func() {
Registers a callback to execute asynchronously when the context signals cancellation.
2
if stopFunc() {
Attempts to unregister the completion callback; returns true if unregistration succeeded prior to execution.