mirror of https://github.com/shirou/gopsutil
commit
e25aa96aad
@ -0,0 +1,18 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Sleep awaits for provided interval.
|
||||||
|
// Can be interrupted by context cancelation.
|
||||||
|
func Sleep(ctx context.Context, interval time.Duration) error {
|
||||||
|
var timer = time.NewTimer(interval)
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-timer.C:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package common_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/shirou/gopsutil/internal/common"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSleep(test *testing.T) {
|
||||||
|
const dt = 50 * time.Millisecond
|
||||||
|
var t = func(name string, ctx context.Context, expected error) {
|
||||||
|
test.Run(name, func(test *testing.T) {
|
||||||
|
var err = common.Sleep(ctx, dt)
|
||||||
|
if err != expected {
|
||||||
|
test.Errorf("expected %v, got %v", expected, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
var ctx = context.Background()
|
||||||
|
var canceled, cancel = context.WithCancel(ctx)
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
t("background context", ctx, nil)
|
||||||
|
t("canceled context", canceled, context.Canceled)
|
||||||
|
}
|
Loading…
Reference in New Issue