TimerTask的两个重要函数
cancel();
作用:取消TimerTask任务
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask {
private int i = 0;
@Override
public void run() {
i++;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
System.out.println("Current Time:"+format.format(calendar.getTime()));//获取当前系统时间
System.out.println("NO.1");
if(i==4)
{
cancel();
}
}
public static void main(String[] args) {
MyTimerTask task = new MyTimerTask();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
System.out.println(format.format(calendar.getTime()));
//calendar.add(Calendar.SECOND,3);//获取距离当前时间3秒后的时间
Timer timer = new Timer();
timer.schedule(task,0,1000);
}
}
scheduleExecutionTime()
作用:返回此任务最近实际执行安排的时间,返回类型为long
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask {
private int i = 0;
@Override
public void run() {
i++;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
System.out.println("Current Time:"+format.format(calendar.getTime()));//获取当前系统时间
System.out.println("NO.1");
if(i==4)
{
cancel();
}
}
public static void main(String[] args) {
MyTimerTask task = new MyTimerTask();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
System.out.println(format.format(calendar.getTime()));
//calendar.add(Calendar.SECOND,3);//获取距离当前时间3秒后的时间
Timer timer = new Timer();
timer.schedule(task,3000);
System.out.println(format.format(task.scheduledExecutionTime()));
}
}