2008-12-03 17:40:00 -07:00
|
|
|
// Copyright 2009 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package time
|
|
|
|
|
|
|
|
import (
|
|
|
|
"syscall";
|
2008-12-09 11:57:55 -07:00
|
|
|
"time";
|
|
|
|
"unsafe";
|
2008-12-03 17:40:00 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
// TODO(rsc): This implementation of time.Tick is a
|
|
|
|
// simple placeholder. Eventually, there will need to be
|
|
|
|
// a single central time server no matter how many tickers
|
|
|
|
// are active. There also needs to be a way to cancel a ticker.
|
|
|
|
//
|
|
|
|
// Also, if timeouts become part of the select statement,
|
|
|
|
// perhaps the Ticker is just:
|
|
|
|
//
|
2008-12-19 04:05:37 -07:00
|
|
|
// func Ticker(ns int64, c chan int64) {
|
2008-12-03 17:40:00 -07:00
|
|
|
// for {
|
|
|
|
// select { timeout ns: }
|
|
|
|
// nsec, err := time.Nanoseconds();
|
|
|
|
// c <- nsec;
|
|
|
|
// }
|
|
|
|
|
2009-01-16 11:14:12 -07:00
|
|
|
func ticker(ns int64, c chan int64) {
|
2008-12-03 17:40:00 -07:00
|
|
|
var tv syscall.Timeval;
|
2008-12-08 18:45:50 -07:00
|
|
|
now := time.Nanoseconds();
|
|
|
|
when := now;
|
2008-12-03 17:40:00 -07:00
|
|
|
for {
|
2008-12-08 18:45:50 -07:00
|
|
|
when += ns; // next alarm
|
2008-12-09 11:57:55 -07:00
|
|
|
|
2008-12-08 18:45:50 -07:00
|
|
|
// if c <- now took too long, skip ahead
|
|
|
|
if when < now {
|
|
|
|
// one big step
|
|
|
|
when += (now-when)/ns * ns;
|
|
|
|
}
|
|
|
|
for when <= now {
|
|
|
|
// little steps until when > now
|
|
|
|
when += ns
|
|
|
|
}
|
|
|
|
|
2009-02-16 17:32:30 -07:00
|
|
|
time.Sleep(when - now);
|
2008-12-08 18:45:50 -07:00
|
|
|
now = time.Nanoseconds();
|
|
|
|
c <- now;
|
2008-12-03 17:40:00 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2009-01-20 15:40:40 -07:00
|
|
|
func Tick(ns int64) chan int64 {
|
2008-12-08 18:45:50 -07:00
|
|
|
if ns <= 0 {
|
|
|
|
return nil
|
|
|
|
}
|
2009-01-06 16:19:02 -07:00
|
|
|
c := make(chan int64);
|
2009-01-16 11:14:12 -07:00
|
|
|
go ticker(ns, c);
|
2008-12-03 17:40:00 -07:00
|
|
|
return c;
|
|
|
|
}
|
|
|
|
|