tick.go 1.33 KB
Newer Older
Russ Cox's avatar
Russ Cox committed
1 2 3 4 5 6 7 8
// 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";
9
	"unsafe";
Russ Cox's avatar
Russ Cox committed
10 11
)

12
// TODO(rsc): This implementation of Tick is a
Russ Cox's avatar
Russ Cox committed
13 14 15 16 17 18 19
// 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:
//
20
//	func Ticker(ns int64, c chan int64) {
Russ Cox's avatar
Russ Cox committed
21 22
//		for {
//			select { timeout ns: }
23
//			nsec, err := Nanoseconds();
Russ Cox's avatar
Russ Cox committed
24 25 26
//			c <- nsec;
//		}

Russ Cox's avatar
Russ Cox committed
27
func ticker(ns int64, c chan int64) {
Russ Cox's avatar
Russ Cox committed
28
	var tv syscall.Timeval;
29
	now := Nanoseconds();
30
	when := now;
Russ Cox's avatar
Russ Cox committed
31
	for {
32
		when += ns;	// next alarm
33

34 35 36 37 38 39 40 41 42 43
		// 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
		}

44 45
		Sleep(when - now);
		now = Nanoseconds();
46
		c <- now;
Russ Cox's avatar
Russ Cox committed
47 48 49
	}
}

Rob Pike's avatar
Rob Pike committed
50 51 52
// Tick creates a synchronous channel that will send the time, in nanoseconds,
// every ns nanoseconds.  It adjusts the intervals to make up for pauses in
// delivery of the ticks.
Russ Cox's avatar
Russ Cox committed
53
func Tick(ns int64) chan int64 {
54 55 56
	if ns <= 0 {
		return nil
	}
Russ Cox's avatar
Russ Cox committed
57
	c := make(chan int64);
Russ Cox's avatar
Russ Cox committed
58
	go ticker(ns, c);
Russ Cox's avatar
Russ Cox committed
59 60 61
	return c;
}