Skip to content
This repository has been archived by the owner on Nov 21, 2023. It is now read-only.

Commit

Permalink
optimized functions DelayContext, DelayAfterContext for timer perform…
Browse files Browse the repository at this point in the history
…ance
  • Loading branch information
orkunkaraduman committed Jul 4, 2022
1 parent e6780fe commit d45b8c7
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions xcontext.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ import (
// Calling the cancel function is not necessary.
func DelayContext(ctx context.Context, delay time.Duration) (context.Context, context.CancelFunc) {
newCtx, newCtxCancel := context.WithCancel(context.Background())
delayTimer := time.NewTimer(delay)
go func() {
parentCtx := ctx
parentCtxOk := context.Background()
delayCh := time.After(delay)
delayCh := delayTimer.C
delayOkCh := make(<-chan time.Time)
for done := false; !done; {
select {
Expand All @@ -35,6 +36,7 @@ func DelayContext(ctx context.Context, delay time.Duration) (context.Context, co
}
}
newCtxCancel()
delayTimer.Stop()
}()
return newCtx, newCtxCancel
}
Expand All @@ -51,16 +53,19 @@ func DelayContext2(ctx context.Context, delay time.Duration) context.Context {
// Calling the cancel function is not necessary.
func DelayAfterContext(ctx context.Context, delay time.Duration) (context.Context, context.CancelFunc) {
newCtx, newCtxCancel := context.WithCancel(context.Background())
delayTimer := time.NewTimer(0)
if !delayTimer.Stop() {
<-delayTimer.C
}
go func() {
parentCtx := ctx
parentCtxOk := context.Background()
delayCh := make(<-chan time.Time)
for done := false; !done; {
select {
case <-parentCtx.Done():
parentCtx = parentCtxOk
delayCh = time.After(delay)
case <-delayCh:
delayTimer.Reset(delay)
case <-delayTimer.C:
if parentCtx == parentCtxOk {
done = true
}
Expand All @@ -69,6 +74,7 @@ func DelayAfterContext(ctx context.Context, delay time.Duration) (context.Contex
}
}
newCtxCancel()
delayTimer.Stop()
}()
return newCtx, newCtxCancel
}
Expand Down

0 comments on commit d45b8c7

Please sign in to comment.