Download source code and Examples
1 principle: Start a thread to brush the time. The disadvantage is that it is not accurate and may be related to the thread priority.
There will be an error of 0 to 10 ms. Accurate to S is no problem.
Package timer;
Public class timer ...{
Private long interval;
// Private Boolean enabled;
Private task;
Private Clock;
Public timer (long _ interval, task _ task )...{
Super ();
This. interval = _ interval;
// This. Enabled = enabled;
This. Task = _ task;
Clock = new clock ();
Clock. Start ();
New thread (New runnable ()...{
Public void run ()...{
Boolean B = true;
While (B )...{
// System. Out. println (clock. getcurrtime ());
If (interval <= clock. getcurrtime ())...{
System. Out. println (clock. getcurrtime ());
Task. doit ();
Clock. setcurrtime (0 );
// Clock. Stop ();
// System. Out. println (clock. getcurrtime ());
// B = false;
}
}
}
}). Start ();
}
Public task gettask ()...{
Return task;
}
Public long getinterval ()...{
Return interval;
}
// Public Boolean isenabled (){
// Return enabled;
//}
// Public void setenabled (Boolean enabled ){
// This. Enabled = enabled;
//}
}
Package timer;
Public class clock extends thread ...{
Private long oldtime;
Private long currtime;
Public clock ()...{
Oldtime = system. currenttimemillis ();
Currtime = 0;
}
Public long getcurrtime ()...{
Return currtime;
}
@ Override
Public void run ()...{
While (true )...{
Currtime = system. currenttimemillis ()-oldtime;
}
}
Public void setcurrtime (long currtime )...{
This. currtime = currtime;
}
}
Package timer;
Public interface task ...{
Void doit ();
}
Package timer;
Public class newtask implements task ...{
Public void doit ()...{
System. Out. println (system. currenttimemillis ());
}
}
Package timer;
Public class test ...{
/***//**
* @ Param ARGs
*/
Public static void main (string [] ARGs )...{
Task task = new newtask ();
Timer T = new timer (1000, task );
}
}