1

I really seek a logical explanation regarding the following. I have a timed task

static TimerTask timedTask = new TimerTask() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("timed task");
    }
};

Timer timer = new Timer();
timer.schedule(timedTask, (long) logfile.getFileHash().get(1).getTimeStampInNano());

when i run that code, nothing shows up in the console, but wen I change it to:

Timer timer = new Timer();
timer.schedule(timedTask, (long) logfile.getFileHash().get(1).getTimeStampInMilli());

the console displays the message in the run() method. It seems to me that the system could not manage to handle time in nanoseconds because they are faster than the system clock. But how it is possible while there is a method called System.nanoTime(), which means the system should be able to recognize that a tasks starts at specific nano seconds.

David ten Hove
  • 2,748
  • 18
  • 33
Amrmsmb
  • 1
  • 27
  • 104
  • 226

2 Answers2

4

I'm not sure I understand the actual question, and the information given in the accepted answer looks correct as far as it goes. But for the method Timer.schedule(TimerTask, long), the long value is a delay measured in milliseconds. It does not know or care whether the long was originally a number of nanoseconds. Since that is billionths of a second instead of thousandths, you're going to wait many orders of magnitude longer than if it were in milliseconds.

arcy
  • 12,845
  • 12
  • 58
  • 103
  • I think you nailed the problem; the OP simply hasn't waited long enough, due to the (much) larger number involved in nano-time... – Anders R. Bystrup Dec 03 '14 at 14:25
  • 1
    The thing about it is, even a millisecond value that represented a date would create a delay longer than anyone is liable to wait. But I don't know whether that's what the long represents, I'm deducing that from the "getTimeStamp" part of the method name. – arcy Dec 03 '14 at 14:32
  • Now that I look at the original question again (did someone edit it for content), OP is expecting the task to start at a particular time. Someone should therefore tell him not to cast his value to `long`, it needs to be a `Date`. – arcy Dec 03 '14 at 22:01
3

The api documentation on System.nanoTime() says:

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().

As such, the JVM might not be able to see difference in time that are smaller than 1 millisecond.

David ten Hove
  • 2,748
  • 18
  • 33
  • This doesn't answer the question, which is about providing nanoseconds as an argument where milliseconds are expected by the function. – vinntec Apr 03 '16 at 18:18