Skip to content

Commit

Permalink
Added Deadline methods
Browse files Browse the repository at this point in the history
  • Loading branch information
ekoutanov committed Apr 19, 2020
1 parent fa6dacf commit 6ed8ca3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
13 changes: 10 additions & 3 deletions concurrent/deadline.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -75,12 +76,18 @@ 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
}

// Move the timestamp of the last run to the new time.
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()
}
10 changes: 6 additions & 4 deletions concurrent/deadline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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() {
Expand Down

0 comments on commit 6ed8ca3

Please sign in to comment.