timer和ScheduledThreadPoolExecutor定时任务和每日固定时间执行
//ScheduledThreadPoolExecutor每三秒执行一次
public static void main(String[] args) {
ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2);
scheduled.scheduleAtFixedRate(new Runnable() {
int i = 0;
@Override
public void run() {
System.out.println("执行"+i++);
}
},0,3000,TimeUnit.MILLISECONDS);
}
//timer每三秒执行一次
public static void main(String[] args) {
Date sendDate = new Date();
Timer dTimer = new Timer();
dTimer.schedule(new TimerTask() {
@Override
int i = 0;
public void run() {
System.out.print("执行"+i++);
}
}, sendDate,3000);
}
//timer每日定时执行一次
public static void main(String[] args) {
long daySpan = 24 * 60 * 60 * 1000;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 15:29:00");
try {
Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
if (System.currentTimeMillis() > startTime.getTime()){
startTime = new Date(startTime.getTime() + daySpan);
}
Timer t = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.print("定时器执行");
}
};
t.schedule(task, startTime, daySpan);
} catch (Exception e) {
e.printStackTrace();
}
}