开发者

What is the best timer technique for exact one second intervals?

I am writing a simple timekeeping app for a specialized outdoor sport. The app performs a series of calculations every second, and displays information of interest to the user. Elapsed time is key to the accuracy of the calculated results. Ideally the开发者_运维问答 calculation and results would be updated exactly every second. I have tried using a timer or a chronometer widget to control the update interval:

Is there a more accurate way to establish the interval? Is there a technique that will give me a nearly exact one second interval?

The code below is not complete - just an effort to show the type of time and chronometer I am using - they run fine, they are just not precise.

import java.util.Timer ;
import java.util.TimerTask;
...
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
public void run() {
...
TimerMethod();
}
}, 0, 1000);
... 
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
...
private Runnable Timer_Tick = new Runnable() {
public void run() {
blah blah
}

///////////////////////////////

import android.widget.Chronometer;
...
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
final TextView keyBox = (TextView)findViewById(R.id.keyBox);
...      
myChronometer.start();
...   
myChronometer.setOnChronometerTickListener(
new Chronometer.OnChronometerTickListener(){
...
public void onChronometerTick(Chronometer myChronometer) {
blah blah             
}


Did you look at the scheduleAtFixedRate method of java.util.Timer class?

According to javadoc, "In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate)."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜