Java定时任务
一、Java原生定时任务
使用 java.util.Timer
和 java.util.TimerTask
类来创建传统的 Java 定时任务
public class JavaTimerTask {
//多线程并行处理定时任务时,Timer运行多个TimeTask时,只要其中之一没有捕获抛出的异常,其它任务便会自动终止运行,使用ScheduledExecutorService则没有这个问题。
public static void main(String[] args) {
Timer timer = new Timer();
// 延迟1秒后开始执行任务,每隔2秒执行一次
timer.schedule(new JavaTask(), 1000, 2000);
}
//继承接口 TimerTask
static class JavaTask extends TimerTask {
@Override
public void run() {
LocalDateTime now = LocalDateTime.now();
int second = now.getSecond();
if (second >= 50) {
throw new RuntimeException("定时任务发生异常");
}
System.out.println("Java原生定时任务: " + now);
}
}
}
二、SpringBoot定时任务
在启动类上加上 @EnableScheduling
注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
使用与 Spring 相同的 @Scheduled
注解来定义定时任务
@Component
public class SpringBootTimerTask {
@Scheduled(initialDelay = 1000, fixedRate = 2000) // 延迟1秒后开始执行任务,每隔2秒执行一次
public static void run() {
LocalDateTime now = LocalDateTime.now();
int second = now.getSecond();
if (second >= 50) {
System.out.println("定时任务发生异常: " + now);
throw new RuntimeException("定时任务发生异常");
}
System.out.println("Java原生定时任务: " + now);
}