import java.sql.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.util.Log;
public abstract class JTimer {
private static final String DEBUG_TAG="JTimer";
private static final boolean DEBUG_ENABLE=true;
private Timer mTimer;
private boolean mRunOneTimeFlag;
public abstract void onTimer();
public JTimer(){
mTimer=null;
mRunOneTimeFlag=false;
}
/**
* Schedule a task for single execution. If 'when' is less than the current time, it will
* be scheduled to be executed as soon as possible.
* @param when time of execution
* @return 0 if it is scheduled succeeded.
*/
public int schedule(Date when){
if(mTimer!=null){
// Log.w(DEBUG_TAG, "In schedule(Date when): Timer is running.");
// return -1;
stop();
}
mRunOneTimeFlag=true;
mTimer=new Timer();
mTimer.schedule(new cTask(), when);
return 0;
}
/**
* Schedule a task for single execution (callback in function onTimer() ) after a specified delay.
* @param delay amount of time in milliseconds before execution.
* @return 0 if schedule succeeded.
*/
public int schedule(long delay){
if(mTimer!=null){
// Log.w(DEBUG_TAG, "In schedule(long delay): Timer is running.");
// return -1;
stop();
}
mRunOneTimeFlag=true;
mTimer=new Timer();
mTimer.schedule(new cTask(), delay);
return 0;
}
/**
* Schedule a task for repeated fixed-rate execution
* after specific time be reached.
*
* @param when time of execution.
* @param period amount of time in milliseconds between subsequent execution.
* @return 0 if schedule succeeded.
*/
public int schedule(Date when,long period){
if(mTimer!=null){
stop();
}
mTimer=new Timer();
mTimer.schedule(new cTask(), when, period);
return 0;
}
/**
* Schedule a task for repeated fixed-rate execution
* after specific delay has passed.
*
* @param delay amount of time in milliseconds before first execution.
* @param period amount of time in milliseconds between subsequent execution.
* @return
*/
public int schedule(long delay,long period){
if(mTimer!=null){
stop();
}
mTimer=new Timer();
mTimer.schedule(new cTask(), delay, period);
return 0;
}
/**
* Stop the timer and its task.
* @return 0 if the timer is stopped.
*/
public int stop(){
if(mTimer==null){
Log.w(DEBUG_TAG, "In stop(): Timer isn't running.");
return -1;
}
mTimer.cancel();
// mTimer.purge();
mTimer=null;
if(DEBUG_ENABLE) Log.i(DEBUG_TAG, "In stop(): Timer is be stopped");
return 0;
}
/**
* The timer is scheduled or not.
* @return true for timer is scheduled, otherwise false.
*/
public boolean isScheduled(){
if(mTimer == null) return false;
return true;
}
class cTask extends TimerTask{
@Override
public void run() {
onTimer();
if(mRunOneTimeFlag){
stop();
}
mRunOneTimeFlag=false;
}
}
}
2014年3月10日 星期一
JTimer
訂閱:
張貼留言
(
Atom
)
沒有留言 :
張貼留言