一、介绍
在应用里经常都有用到在后台跑定时任务的需求。比如网络运营商会在每个月的一号对数据进行一次统计。在java中我们可以继承timertask类来实现定时任务。
二、笔记
/**
* 定时任务
* 1.继承timertask(runable)的子类
* 2.重写run方法
* 3.在run方法中编写自己的业务
* 4.通过timer类提供的方法来启动定时任务
* @author HuTiger
*
*/
public class TimeTask extends TimerTask { private Timer timer;
private TimerTask task; public static void main(String[] args) {
TimeTask t = new TimeTask();
// t.start();
SimpleDateFormat sdDateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
Date date;
try {
date = sdDateFormat.parse("2016-09-23 15:32:00");
t.start(date);
} catch (ParseException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} } @Override
public void run() {
// TODO 自动生成的方法存根 } public void start(Date date) {
if (timer == null) {
timer = new Timer();
}
if (task == null) {
task = new myTimer();
}
timer.schedule(task, date); //在程序启动后,一定时间内开始执行
timer.schedule(task, 5000,1000);
//如果设置的时间已经过时,那么将从当前时间开始运行
timer.schedule(task, date,1000);
//如果设置的时候已经过时,那么将从设置时间开始执行,把之前没有完成的补齐
timer.scheduleAtFixedRate(task, date, 1000);
} public void stop() {
if (task != null) {
task.cancel();
}
if (timer != null) {
timer.cancel();
}
task=null;
timer=null;
}
} class myTimer extends TimerTask {
@Override
public void run() {
// TODO 自动生成的方法存根
System.out.println("定时执行的任务");
}
}