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ù)在指定的時間開始進行重復的固定延遲執(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í)行的延時時間
// 3、任務(wù)執(zhí)行間隔 4、間隔時間單位
service.scheduleAtFixedRate(()->System.out.println("task ScheduledExecutorService "+ timeString), 3, 1, TimeUnit.SECONDS);
}
}
3、使用Spring Task
在啟動類上使用@EnableScheduling注解開啟對定時任務(wù)的支持,然后啟動項目
@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:表明該類是一個配置類
@EnableAsync:開啟異步事件的支持
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。