mirror of https://github.com/shirou/gopsutil
use cancelable sleep in cpu.PercentWithContext and process.Process.PercentWithContext
parent
e1925b853e
commit
34df4904f6
@ -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,29 @@
|
||||
package common_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"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 !errors.Is(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