-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #34 from pior/every
Rewrite Periodic() into a nicer Every()
- Loading branch information
Showing
5 changed files
with
47 additions
and
56 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,38 @@ | ||
package runnable | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"time" | ||
) | ||
|
||
// Every returns a runnable that will periodically run the runnable passed in argument. | ||
func Every(runnable Runnable, period time.Duration) Runnable { | ||
return &every{runnable, period} | ||
} | ||
|
||
type every struct { | ||
runnable Runnable | ||
period time.Duration | ||
} | ||
|
||
func (e *every) Run(ctx context.Context) (err error) { | ||
ticker := time.NewTicker(e.period) | ||
|
||
for { | ||
select { | ||
case <-ctx.Done(): | ||
ticker.Stop() | ||
return ctx.Err() | ||
case <-ticker.C: | ||
err := e.runnable.Run(ctx) | ||
if err != nil { | ||
return err | ||
} | ||
} | ||
} | ||
} | ||
|
||
func (e *every) name() string { | ||
return composeName(fmt.Sprintf("every[%s]", e.period), e.runnable) | ||
} |
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
This file was deleted.
Oops, something went wrong.