-
Notifications
You must be signed in to change notification settings - Fork 246
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Rewrite concurrent downloader and make erc20 downloader concurrent
- Loading branch information
Showing
5 changed files
with
197 additions
and
131 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
package wallet | ||
|
||
import ( | ||
"context" | ||
"sync" | ||
"time" | ||
) | ||
|
||
type Command interface { | ||
Run(context.Context) | ||
} | ||
|
||
type FiniteCommand struct { | ||
Interval time.Duration | ||
Runable func(context.Context) error | ||
} | ||
|
||
func (c FiniteCommand) Run(ctx context.Context) { | ||
ticker := time.NewTicker(c.Interval) | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
return | ||
case <-ticker.C: | ||
err := c.Runable(ctx) | ||
if err == nil { | ||
return | ||
} | ||
} | ||
} | ||
} | ||
|
||
type InfiniteCommand struct { | ||
Interval time.Duration | ||
Runable func(context.Context) error | ||
} | ||
|
||
func (c InfiniteCommand) Run(ctx context.Context) { | ||
ticker := time.NewTicker(c.Interval) | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
return | ||
case <-ticker.C: | ||
_ = c.Runable(ctx) | ||
} | ||
} | ||
} | ||
|
||
func NewGroup() *Group { | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
return &Group{ | ||
ctx: ctx, | ||
cancel: cancel, | ||
} | ||
} | ||
|
||
type Group struct { | ||
ctx context.Context | ||
cancel func() | ||
wg sync.WaitGroup | ||
} | ||
|
||
func (g *Group) Add(cmd Command) { | ||
g.wg.Add(1) | ||
go func() { | ||
cmd.Run(g.ctx) | ||
g.wg.Done() | ||
}() | ||
} | ||
|
||
func (g *Group) Stop() { | ||
g.cancel() | ||
g.wg.Wait() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.