Clocks and Time

From Suhrid.net Wiki
Revision as of 10:45, 11 December 2011 by Suhridk (talk | contribs) (→‎Intro)
Jump to navigationJump to search

Intro

  • Absolute Time - Represents a specific point in time given by milliseconds plus nanoseconds past some point in time fixed by the clock. For the default real-time clock the fixed point is the Epoch (January 1, 1970, 00:00:00 GMT)
  • Relative Time - Represents a time interval milliseconds + nanoseconds seconds long. It generally is used to represent a time relative to now.
  • Standard Java only has a wall clock - calendar time. But real time systems require:
    • A monotonic clock.
    • A countdown clock.
    • A CPU execution time clock - measures amount of CPU time consumed by a particular thread or object.
  • Time is supported through the HighResolutionTime abstract class. Three implementing concrete classes - absolute, relative and rational.
  • Clock is supported through an abstract Clock class.
  • HighResolutionTime offers conversion between absolute and relative time values.
import java.util.Calendar;
import java.util.Date;

import javax.realtime.*;

public class TimeTest2 {

	public static void main(String[] args) {
		
		Clock clock = Clock.getRealtimeClock();
		
		Calendar cal = Calendar.getInstance();
		cal.set(2012, 0, 1, 0, 0, 0);
		Date newYear2012 = cal.getTime();
		
		AbsoluteTime at = new AbsoluteTime(newYear2012);
		
		//Convert absolute to relative
		RelativeTime rt = at.relative(clock);
		
		System.out.println("The number of ms between now and new year 2012 " + rt);
		
		//To confirm - add the current time and the relative time and we'll get new year 2012.
		Date d = new Date(System.currentTimeMillis() + rt.getMilliseconds());
		System.out.println(d);
		
		long oneweekms = 86400 * 7 * 1000;
		RelativeTime oneweek = new RelativeTime(oneweekms, 0);
		
		//Convert relative to absolute
		AbsoluteTime abs = oneweek.absolute(clock);
		
		//Will print an absolute date one week from now
		System.out.println(abs.getDate());
	}
}