added extend

This commit is contained in:
Karl Seguin 2014-10-27 08:27:26 +07:00
parent 77765a3f11
commit 0fddc964ec
3 changed files with 26 additions and 6 deletions

17
item.go
View file

@ -13,6 +13,7 @@ type TrackedItem interface {
Expired() bool
TTL() time.Duration
Expires() time.Time
Extend(duration time.Duration)
}
type nilItem struct{}
@ -32,6 +33,9 @@ func (i *nilItem) Expires() time.Time {
return time.Time{}
}
func (i *nilItem) Extend(duration time.Duration) {
}
var NilTracked = new(nilItem)
type Item struct {
@ -70,13 +74,20 @@ func (i *Item) Release() {
}
func (i *Item) Expired() bool {
return i.expires < time.Now().Unix()
expires := atomic.LoadInt64(&i.expires)
return expires < time.Now().Unix()
}
func (i *Item) TTL() time.Duration {
return time.Second * time.Duration(i.expires - time.Now().Unix())
expires := atomic.LoadInt64(&i.expires)
return time.Second * time.Duration(expires - time.Now().Unix())
}
func (i *Item) Expires() time.Time {
return time.Unix(i.expires, 0)
expires := atomic.LoadInt64(&i.expires)
return time.Unix(expires, 0)
}
func (i *Item) Extend(duration time.Duration) {
atomic.StoreInt64(&i.expires, time.Now().Add(duration).Unix())
}

View file

@ -34,9 +34,15 @@ func (i *ItemTests) TTL() {
Expect(item2.TTL()).To.Equal(time.Second * -10)
}
func (i *ItemTests) Expires() {
now := time.Now().Unix()
item1 := &Item{expires: now + 10}
Expect(item1.Expires().Unix()).To.Equal(now + 10)
item := &Item{expires: now + 10}
Expect(item.Expires().Unix()).To.Equal(now + 10)
}
func (i *ItemTests) Extend() {
item := &Item{expires: time.Now().Unix() + 10}
item.Extend(time.Minute * 2)
Expect(item.Expires().Unix()).To.Equal(time.Now().Unix() + 120)
}

View file

@ -89,6 +89,9 @@ item, err := cache.Fetch("user:4", time.Minute * 10, func() (interface{}, error)
cache.Delete("user:4")
```
### Extend
The life of an item can be changed via the `Extend` method. This will change the expiry of the item by the specified duration relative to the current time.
## Tracking
CCache supports a special tracking mode which is meant to be used in conjunction with other pieces of your code that maintains a long-lived reference to data.