在 Java 中实现定时任务有多种方式,最常用的包括:
1.使用 java.util.Timer 和 TimerTask
2.使用 ScheduledExecutorService 使用 Spring 的
3.@Scheduled 注解
4. 使用 Quartz 框架
下面我将为你分别展示这四种方法的具体代码示例:
1. 使用 java.util.Timer 和 TimerTask
Timer 是一个基于单线程的简单定时任务调度工具,适合执行较简单的周期性任务。
import java.util.Timer;
import java.util.TimerTask;
public class TimerExample {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Task executed at: " + System.currentTimeMillis());
}
};
// 每隔 2 秒执行一次任务
timer.scheduleAtFixedRate(task, 0, 2000);
}
}
2. 使用 ScheduledExecutorService
ScheduledExecutorService 是一个更强大的定时任务工具,可以指定初始延迟、固定频率或固定延迟执行任务。
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorServiceExample {
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable task = () -> System.out.println("Task executed at: " + System.currentTimeMillis());
// 延迟 1 秒后每 3 秒执行一次任务
scheduler.scheduleAtFixedRate(task, 1, 3, TimeUnit.SECONDS);
}
}
3. 使用 Spring 的 @Scheduled 注解
如果你在使用 Spring 框架,可以使用 @Scheduled 注解来配置定时任务。Spring 会自动处理任务调度,支持多种配置方式(如固定速率、固定延迟、Cron 表达式)。
首先,你需要在 Spring Boot 项目中启用定时任务:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class ScheduledTaskApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduledTaskApplication.class, args);
}
}
然后创建一个带有定时任务的组件:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
// 每 5 秒执行一次
@Scheduled(fixedRate = 5000)
public void fixedRateTask() {
System.out.println("Fixed rate task executed at: " + System.currentTimeMillis());
}
// 上一个任务执行完后延迟 2 秒再执行
@Scheduled(fixedDelay = 2000)
public void fixedDelayTask() {
System.out.println("Fixed delay task executed at: " + System.currentTimeMillis());
}
// 使用 Cron 表达式:每分钟的第 0, 15, 30, 45 秒执行
@Scheduled(cron = "0,15,30,45 * * * * ?")
public void cronTask() {
System.out.println("Cron task executed at: " + System.currentTimeMillis());
}
}
4. 使用 Quartz 框架
Quartz 是一个功能强大的任务调度框架,适用于更复杂和高需求的调度任务。它支持分布式环境,并且可以持久化任务。
<!-- 添加 Quartz 依赖 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzExample {
public static void main(String[] args) throws SchedulerException {
JobDetail job = JobBuilder.newJob(SimpleJob.class)
.withIdentity("simpleJob")
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("simpleTrigger")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(5) // 每5秒执行一次
.repeatForever())
.build();
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
public static class SimpleJob implements Job {
@Override
public void execute(JobExecutionContext context) {
System.out.println("Quartz job executed at: " + System.currentTimeMillis());
}
}
}
总结
以上就是 Java 中实现定时任务的几种方式,根据你的具体需求可以选择适合的方式。
注意:此文章为学习记录文章,参考多篇文章,如有不正之处请指教