import java.util.Timer;
import java.util.TimerTask;
/**
* @description: 测试使用单线程定时器
*/
public class TestTimer {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("test...");
}
}, 1000L, 1000L);
}
}
package com.spiov.cloud.test;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @description: 测试使用线程池定时器
*/
public class TestScheduled {
public static void main(String[] args) throws InterruptedException {
//创建大小为5的线程池
ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(5);
Task worker = new Task("task");
// 只执行一次
// scheduledPool.schedule(worker, 5, TimeUnit.SECONDS);
// 周期性执行,每1秒执行一次
scheduledPool.scheduleAtFixedRate(worker, 0,1, TimeUnit.SECONDS);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
System.out.println("Shutting down executor...");
// 关闭线程池
scheduledPool.shutdown();
boolean isDone;
// 等待线程池终止
do {
isDone = scheduledPool.awaitTermination(1, TimeUnit.DAYS);
System.out.println("awaitTermination...");
} while(!isDone);
System.out.println("Finished all threads");
}
}
class Task implements Runnable {
private String name;
public Task(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("threadName = "+Thread.currentThread().getName()+",taskName = " + name + ", startTime = " + LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
}
}