github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/clock.go (about)

     1  /*
     2  Copyright 2014 The Kubernetes Authors All rights reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package util
    18  
    19  import (
    20  	"time"
    21  )
    22  
    23  // Clock allows for injecting fake or real clocks into code that
    24  // needs to do arbitrary things based on time.
    25  type Clock interface {
    26  	Now() time.Time
    27  	Since(time.Time) time.Duration
    28  }
    29  
    30  // RealClock really calls time.Now()
    31  type RealClock struct{}
    32  
    33  // Now returns the current time.
    34  func (r RealClock) Now() time.Time {
    35  	return time.Now()
    36  }
    37  
    38  // Since returns time since the specified timestamp.
    39  func (r RealClock) Since(ts time.Time) time.Duration {
    40  	return time.Since(ts)
    41  }
    42  
    43  // FakeClock implements Clock, but returns an arbitrary time.
    44  type FakeClock struct {
    45  	Time time.Time
    46  }
    47  
    48  // Now returns f's time.
    49  func (f *FakeClock) Now() time.Time {
    50  	return f.Time
    51  }
    52  
    53  // Since returns time since the time in f.
    54  func (f *FakeClock) Since(ts time.Time) time.Duration {
    55  	return f.Time.Sub(ts)
    56  }
    57  
    58  // Move clock by Duration
    59  func (f *FakeClock) Step(d time.Duration) {
    60  	f.Time = f.Time.Add(d)
    61  }
    62  
    63  // IntervalClock implements Clock, but each invocation of Now steps the clock forward the specified duration
    64  type IntervalClock struct {
    65  	Time     time.Time
    66  	Duration time.Duration
    67  }
    68  
    69  // Now returns i's time.
    70  func (i *IntervalClock) Now() time.Time {
    71  	i.Time = i.Time.Add(i.Duration)
    72  	return i.Time
    73  }
    74  
    75  // Since returns time since the time in i.
    76  func (i *IntervalClock) Since(ts time.Time) time.Duration {
    77  	return i.Time.Sub(ts)
    78  }