java当中提供了Timer
和TimerTask
为我们提供定时任务。
首先继承TimerTask
,重写run()
方法,在该方法内编写我们将要定时执行的任务内容
class MyTask extends TimerTask{
@Override
public void run() {
//编写我们将要定时执行的任务
System.out.println("任务执行...");
}
}
然后实例化MyTask
,调用Timer
的schedule()
方法
各种定时任务如下所示
1.定时任务将在指定时间后执行
public static void main(String[] args) {
MyTask task = new MyTask();
Timer timer = new Timer();
// 定时任务将在5秒后执行
timer.schedule(task, 5000);
}
2.定时任务将在指定时间后执行,并每隔指定的一段时间执行一次
public static void main(String[] args) {
MyTask task = new MyTask();
Timer timer = new Timer();
// 定时任务将在5秒后执行,并每隔1秒执行一次
timer.schedule(task, 5000,1000);
}
3.指定日期执行
public static void main(String[] args) throws ParseException {
MyTask task = new MyTask();
Timer timer = new Timer();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date date = sdf.parse("2022-5-5 16:13");
// 定时任务将在2022-5-5 16:13执行
timer.schedule(task,date);
}
4.指定日期执行,并每隔指定的一段时间执行一次
public static void main(String[] args) throws ParseException {
MyTask task = new MyTask();
Timer timer = new Timer();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date date = sdf.parse("2022-5-5 16:15");
// 定时任务将在2022-5-5 16:15执行,并每隔一秒执行一次
timer.schedule(task,date,1000);
}
当我们打开TimerTask
的源码,会发现其实现的是Runnable
接口,也就是说TimerTask
实现定时任务的方式是基于多线程的
public abstract class TimerTask implements Runnable{
.....
....
.....
}