Looking in class source code java.util.Timer
, these code snippets can be located:
public void schedule(TimerTask task, long delay, long period) {
if (delay < 0)
throw new IllegalArgumentException("Negative delay.");
if (period <= 0)
throw new IllegalArgumentException("Non-positive period.");
sched(task, System.currentTimeMillis()+delay, -period);
}
private void sched(TimerTask task, long time, long period) {
// [um monte de código] ...
task.nextExecutionTime = time;
task.period = period;
task.state = TimerTask.SCHEDULED;
// [mais um monte de código] ...
}
In class TimerThread
(accompanying the class Timer
, but it is not a public class), it is possible to locate the following within the method mainLoop()
:
currentTime = System.currentTimeMillis();
executionTime = task.nextExecutionTime;
if (taskFired = (executionTime<=currentTime)) {
That is, the method schedule
look at the clock (using the method System.currentTimeMillis()
), calculates a time in the future and calls the method sched
, which uses the calculated time to define when the task
shall be implemented. In the mainLoop()
it picks up the time of the clock again (by means of the same method) and checks whether it has passed the time set to run the task
.
This means that changing the date of the clock interferes with the class java.util.Timer
. Changing the date back will postpone the execution of class tasks Timer
. Changing the date forward will cause them to run before the time or even immediately.
The ideal would be to devise a solution based on the method System.nanoTime()
, which means leaving the class java.util.Timer
. The method nanoTime()
does not suffer from this problem as it tells how much time has passed since some arbitrary point of time defined when the JVM is started (at least that’s what the documentation says, but I wouldn’t trust it before testing).
What is the package of this class
Timer
? I ask this because I’ve seen more than one class with that name.– Victor Stafusa
You are using
java.util.Timer
, correct? Doesn’t seem to be thejavax.swing.Timer
.– Victor Stafusa
Hi, thank you for answering. I am using the import java.util.Timer; import java.util.Timertask packages;
– Alessandra Canutto
Remember that changing the date and time should be administrative tasks. If it’s a matter of avoiding fraud, there’s nothing that a dedicated user with administrator powers won’t be able to circumvent.
– Pablo Almeida