【Java】定时任务的几种实现方式

时间:2021-01-01 07:50:11

   第一种的是最简单的,我在写demo和测试的时候经常用,原理就是通过while来无限循环和sleep来控制时间间隔。

public class TimeTask2 {
public static void main(String[] args) {
boolean status = true;
while(status) {
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println(sdf.format(date));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
    第二种是使用java中的定时器Timer,timer的schedule方法可以定时调用继承TimerTask的线程,注意这里间隔不会计算线程运行的时间,但会受线程运行时间影响,线程调用间隔为max(线程运行时间,时间间隔)。

public class TimeTask3 {
private Timer timer;

public void start() {
timer = new Timer();
timer.schedule(new Task(), 0l, 10000l);
}

public void stop() {
if(timer != null) {
timer.cancel();
}
}

public static void main(String[] args) {
new TimeTask3().start();
}

class Task extends TimerTask {
public void run() {
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println(sdf.format(date));
}
}

}

    第三种是使用java的ScheduledExecutorService,调用方式和Timer类似,注意当使用scheduleAtFixedRate时就与TImer相同,使用scheduleWithFixedDelay会在线程运行完成后才重新统计时间间隔,意味着线程运行的间隔为线程运行时间+固定间隔。
public class TimeTask {
private ScheduledExecutorService executor;

public void start() {
executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "test");
}
});
executor.scheduleAtFixedRate(new Task(), 0, 10, TimeUnit.SECONDS);
//executor.scheduleWithFixedDelay(new Task(), 0, 10, TimeUnit.SECONDS);
}

public void stop() {
if(executor != null) {
executor.shutdown();
}
}

public static void main(String[] args) {
new TimeTask().start();
}

class Task implements Runnable {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println(sdf.format(date));
}
}
}