diff --git a/micro/microfunctions.go b/micro/microfunctions.go index 6fc23c5e..8807bbb1 100644 --- a/micro/microfunctions.go +++ b/micro/microfunctions.go @@ -91,6 +91,17 @@ func Pause(ms int) { Sleep(ms) } +// Pause_ctx - приостановка работы программы на нужное число миллисекунд, с учётом глобального контекста +func Pause_ctx(ctx context.Context, ms int) { + + Duration := time.Duration(ms) * time.Millisecond + + select { + case <-ctx.Done(): + case <-time.After(Duration): + } +} + // FindDirUp - возвращает строку с именем каталога на уровень выше func FindDirUp(dir string) string { otvet := dir diff --git a/micro/microfunctions_test.go b/micro/microfunctions_test.go index 7f21811a..2f47015d 100644 --- a/micro/microfunctions_test.go +++ b/micro/microfunctions_test.go @@ -908,3 +908,30 @@ func TestInt32FromString(t *testing.T) { t.Errorf("Expected %d, but got: %d", expected3, result3) } } + +func TestPause_ctx(t *testing.T) { + t.Run("Context canceled before pause duration elapses", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + start := time.Now() + Pause_ctx(ctx, 100) + duration := time.Since(start) + + if duration > 50*time.Millisecond { + t.Errorf("Pause_ctx did not return in a timely manner when context was canceled") + } + }) + + t.Run("Context not canceled before pause duration elapses", func(t *testing.T) { + ctx := context.Background() + + start := time.Now() + Pause_ctx(ctx, 100) + duration := time.Since(start) + + if duration < 100*time.Millisecond { + t.Errorf("Pause_ctx did not wait for the specified duration when context was not canceled") + } + }) +}