Hi, this is a try to do a more precise timer than System.currentTimeMillis
public class Timer implements Runnable
{
private long lastTime;
private long newTime;
private long lastDiff;
private long lastCount;
private long count;
private boolean run;
private Thread process;
public Timer()
{
this.lastCount=1;
this.count=0;
this.lastTime=System.currentTimeMillis();
this.newTime=System.currentTimeMillis();
this.process=new Thread(this);
this.process.start();
this.process.setPriority(Thread.MAX_PRIORITY);
}
public void start()
{
}
public long getTime()
{
if(this.lastCount==0)
return 0;
long predicted=this.lastTime-this.lastDiff+this.count*this.lastDiff/this.lastCount;
if(predicted<this.newTime)
return predicted;
return this.newTime;
}
public void run()
{
while(true)
{
this.setClock();
try
{
Thread.sleep(1);
}
catch(InterruptedException ie)
{
return;
}
}
}
private void setClock()
{
this.newTime=System.currentTimeMillis();
if(this.newTime>this.lastTime)
{
this.lastCount=this.count;
this.count=1;
this.lastDiff=this.newTime-this.lastTime;
this.lastTime=this.newTime;
}
else
{
this.count++;
}
}
}
here a code to test
this.t=new Timer();
int nbLoop=100;
long systemTimes[]=new long[nbLoop];
long timerTimes[]=new long[nbLoop];
long diffTimes[]=new long[nbLoop];
long systemTime=System.currentTimeMillis();
long timerTime=t.getTime();
for(int n=0;n<nbLoop;n++)
{
try
{
Thread.sleep(1); //Replace that to try different interval
}
catch(InterruptedException ie)
{
}
long newSystemTime=System.currentTimeMillis();
long newTimerTime=t.getTime();
systemTimes[n]=newSystemTime-systemTime;
timerTimes[n]=newTimerTime-timerTime;
diffTimes[n]=newSystemTime-newTimerTime;
//timerTime=newTimerTime;
//systemTime=newSystemTime;
}
System.out.println("systemTimes[n]\t\ttimerTimes[n]\t\tdiffTimes[n]");
for(int n=0;n<nbLoop;n++)
{
System.out.println(systemTimes[n]+"\t\t"+timerTimes[n]+"\t\t"+diffTimes[n]);
}