版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhou_fan_xi/article/details/87793278
一 Java 基本的定时任务,总结方法有三种:
1、创建一个thread,然后让它在while循环里一直运行着,通过sleep方法来达到定时任务的效果;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
while (true){
System.out.println("hhh");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
new Thread(runnable).start();
}
结果:从当前时间开始每一秒打印一次hhh。
2、用Timer和TimerTask与第一种方法相比有如下好处:
- 当启动和去取消任务时可以控制
- 第一次执行任务时可以指定你想要的delay时间
2.1、使用 Timer和TimerTask做单循环执行任务
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("hello,nihao");
}
};
Timer timer = new Timer();
//在某个固定的时间之后(int delay)执行
Date parse = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
parse = simpleDateFormat.parse("2019-2-20 14:16:00");
} catch (ParseException e) {
e.printStackTrace();
}
timer.scheduleAtFixedRate(timerTask,parse,1000); //用来停止任务方法
while(true){
try {
int in = System.in.read();
//控制台输入s 结束任务执行 跳出整个循环
if(in == 's'){
//取消任务执行
timer.cancel();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.2、使用 Timer和TimerTask做在每天固定时间执行任务
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("hello,nihao");
}
};
Timer timer = new Timer();
// 一天的毫秒数
long daySpan =24 * 60 * 60 * 1000;
// 规定的每天时间00:30:00运行
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:30:00");
// 首次运行时间
Date startTime = null;
try {
startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
// 如果今天的已经过了 首次运行时间就改为明天
if (startTime.before(new Date())) {
startTime = new Date(startTime.getTime() + daySpan);
}
timer.schedule(timerTask, startTime,daySpan);
}
Timer类的常用其他方法:
cancel()
终止此计时器,丢弃所有当前已安排的任务。
purge()
从此计时器的任务队列中移除所有已取消的任务。
schedule(TimerTask task, Date time)
安排在指定的时间执行指定的任务。
TimerTask类的常用其他方法:
cancel()
取消此计时器任务。
run()
此计时器任务要执行的操作。
scheduledExecutionTime()
返回此任务最近实际 执行的已安排 执行时间。
3 、用ScheduledExecutorService是从的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式,相比于上两个方法,它有以下好处:
- 相比于Timer的单线程,它是通过线程池的方式来执行任务的
- 可以很灵活的去设定第一次执行任务delay时间
- 提供了良好的约定,以便设定执行的时间间隔
public static void main(String[] args){
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("嘻嘻哈哈");
}
};
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.schedule(runnable,1, TimeUnit.DAYS);
}
结果:从当前时间开始执行任务后每24小时后再次循环执行