1、使用Timer
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;
public class TestTimer {
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
LocalDateTime current = LocalDateTime.now();
String timeString = current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("task run:"+ timeString);
}
};
Timer timer = new Timer();
//安排指定的任務(wù)在指定的時(shí)間開始進(jìn)行重復(fù)的固定延遲執(zhí)行。這里是每3秒執(zhí)行一次
timer.schedule(timerTask,3000,1000);
}
}
2趴梢、ScheduledExecutorService
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TestScheduledExecutorService {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
String timeString = current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
// 參數(shù):1、任務(wù)體 2笑窜、首次執(zhí)行的延時(shí)時(shí)間
// 3藐鹤、任務(wù)執(zhí)行間隔 4瓤檐、間隔時(shí)間單位
service.scheduleAtFixedRate(()->System.out.println("task ScheduledExecutorService "+ timeString), 3, 1, TimeUnit.SECONDS);
}
}
3、使用Spring Task
在啟動(dòng)類上使用@EnableScheduling注解開啟對(duì)定時(shí)任務(wù)的支持娱节,然后啟動(dòng)項(xiàng)目
@Slf4j
@Component
public class ScheduledService {
@Scheduled(cron = "0/5 * * * * *")
public void scheduled(){
log.info("=====>>>>>使用cron {}",System.currentTimeMillis());
}
@Scheduled(fixedRate = 5000)
public void scheduled1() {
log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis());
}
@Scheduled(fixedDelay = 5000)
public void scheduled2() {
log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis());
}
}
多線程
@Configuration
@EnableAsync
public class AsyncConfig {
/*
此處成員變量應(yīng)該使用@Value從配置中讀取
*/
private int corePoolSize = 10;
private int maxPoolSize = 200;
private int queueCapacity = 10;
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
@Configuration:表明該類是一個(gè)配置類
@EnableAsync:開啟異步事件的支持