From 6ed8ca396200b2cd421122777551ab1c229f3f12 Mon Sep 17 00:00:00 2001 From: Emil Koutanov Date: Sun, 19 Apr 2020 20:31:05 +1000 Subject: [PATCH] Added Deadline methods --- concurrent/deadline.go | 13 ++++++++++--- concurrent/deadline_test.go | 10 ++++++---- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/concurrent/deadline.go b/concurrent/deadline.go index cdcfb37..ebba09a 100644 --- a/concurrent/deadline.go +++ b/concurrent/deadline.go @@ -35,9 +35,10 @@ func (t *timeCas) set(time time.Time) { type Deadline interface { TryRun(f func()) bool Elapsed() time.Duration - Lapsed() bool + Expired() bool Move(new time.Time) Last() time.Time + Remaining() time.Duration } type deadline struct { @@ -75,8 +76,8 @@ func (d *deadline) Elapsed() time.Duration { return time.Now().Sub(d.Last()) } -// Lapsed returns true if the deadline has lapsed. -func (d *deadline) Lapsed() bool { +// Expired returns true if the deadline has lapsed. +func (d *deadline) Expired() bool { return time.Now().Sub(d.Last()) > d.interval } @@ -84,3 +85,9 @@ func (d *deadline) Lapsed() bool { func (d *deadline) Move(new time.Time) { d.lastRun.set(new) } + +// Remaining returns the duration to the upcoming expiry point. If the deadlines has already lapsed, the returned +// value is negative. +func (d *deadline) Remaining() time.Duration { + return d.interval - d.Elapsed() +} diff --git a/concurrent/deadline_test.go b/concurrent/deadline_test.go index 0dc1bbb..3f9fdc0 100644 --- a/concurrent/deadline_test.go +++ b/concurrent/deadline_test.go @@ -43,12 +43,14 @@ func TestDeadline(t *testing.T) { called = true } assert.Equal(t, zeroTime, d.Last()) - assert.True(t, d.Lapsed()) + assert.True(t, d.Expired()) + assert.LessOrEqual(t, int(d.Remaining()), 0) assert.True(t, d.TryRun(setter)) assert.True(t, called) assert.NotEqual(t, zeroTime, d.Last()) - assert.False(t, d.Lapsed()) + assert.False(t, d.Expired()) + assert.GreaterOrEqual(t, int(d.Remaining()), 0) called = false assert.False(t, d.TryRun(setter)) @@ -60,9 +62,9 @@ func TestDeadline(t *testing.T) { func TestDeadlineMove(t *testing.T) { d := NewDeadline(1 * time.Hour) - assert.True(t, d.Lapsed()) + assert.True(t, d.Expired()) d.Move(time.Now()) - assert.False(t, d.Lapsed()) + assert.False(t, d.Expired()) called := false setter := func() {