本文目录导读:

我来给你介绍几种Java定时模块的通用实现方案,从简单到复杂,涵盖不同场景。
基于 ScheduledExecutorService(推荐)
这是最常用的方式,性能好且灵活:
import java.util.concurrent.*;
import java.util.function.Consumer;
/**
* 通用定时任务管理器
*/
public class TimerManager {
private final ScheduledExecutorService scheduler;
public TimerManager() {
// 创建线程池,可以根据需要调整核心线程数
this.scheduler = Executors.newScheduledThreadPool(
Runtime.getRuntime().availableProcessors(),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "timer-thread");
t.setDaemon(true); // 设置为守护线程
return t;
}
}
);
}
/**
* 延迟执行一次
*/
public ScheduledFuture<?> delay(Runnable task, long delay, TimeUnit unit) {
return scheduler.schedule(task, delay, unit);
}
/**
* 固定频率执行(不等待任务完成)
*/
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task,
long initialDelay,
long period,
TimeUnit unit) {
return scheduler.scheduleAtFixedRate(task, initialDelay, period, unit);
}
/**
* 固定延迟执行(等待任务完成后再计时)
*/
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task,
long initialDelay,
long delay,
TimeUnit unit) {
return scheduler.scheduleWithFixedDelay(task, initialDelay, delay, unit);
}
/**
* 取消任务
*/
public boolean cancelTask(ScheduledFuture<?> future) {
if (future != null && !future.isCancelled()) {
return future.cancel(false);
}
return false;
}
/**
* 优雅关闭
*/
public void shutdown() {
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
} catch (InterruptedException e) {
scheduler.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
使用示例:
public class Demo {
public static void main(String[] args) {
TimerManager timer = new TimerManager();
// 5秒后执行一次
timer.delay(() -> System.out.println("一次性任务"), 5, TimeUnit.SECONDS);
// 每3秒执行一次(固定频率)
ScheduledFuture<?> future = timer.scheduleAtFixedRate(
() -> System.out.println("定时任务执行"),
0, 3, TimeUnit.SECONDS
);
// 10秒后取消任务
timer.delay(() -> timer.cancelTask(future), 10, TimeUnit.SECONDS);
}
}
基于 Quartz 框架(企业级)
适合复杂的定时需求:
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Quartz定时任务管理器
*/
public class QuartzTimerManager {
private final Scheduler scheduler;
public QuartzTimerManager() throws SchedulerException {
this.scheduler = StdSchedulerFactory.getDefaultScheduler();
this.scheduler.start();
}
/**
* 添加Cron表达式任务
*/
public void addCronJob(String jobName, String groupName,
String cronExpression,
Class<? extends Job> jobClass,
JobDataMap dataMap) throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(jobClass)
.withIdentity(jobName, groupName)
.setJobData(dataMap != null ? dataMap : new JobDataMap())
.build();
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity(jobName + "-trigger", groupName)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.build();
scheduler.scheduleJob(jobDetail, trigger);
}
/**
* 添加简单定时任务
*/
public void addSimpleJob(String jobName, String groupName,
Class<? extends Job> jobClass,
int intervalSeconds,
int repeatCount) throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(jobClass)
.withIdentity(jobName, groupName)
.build();
SimpleTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity(jobName + "-trigger", groupName)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(intervalSeconds)
.withRepeatCount(repeatCount))
.build();
scheduler.scheduleJob(jobDetail, trigger);
}
/**
* 移除任务
*/
public boolean removeJob(String jobName, String groupName) {
try {
JobKey jobKey = new JobKey(jobName, groupName);
return scheduler.deleteJob(jobKey);
} catch (SchedulerException e) {
e.printStackTrace();
return false;
}
}
/**
* 关闭调度器
*/
public void shutdown() {
try {
scheduler.shutdown(true);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
// 任务类示例
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println("任务执行时间: " + now);
// 获取参数
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
String param = dataMap.getString("param");
System.out.println("参数: " + param);
}
}
Quartz 使用示例:
public class QuartzDemo {
public static void main(String[] args) throws SchedulerException {
QuartzTimerManager manager = new QuartzTimerManager();
// 每5秒执行一次
manager.addSimpleJob("job1", "group1", MyJob.class, 5, -1);
// 每天中午12点执行(Cron表达式)
JobDataMap dataMap = new JobDataMap();
dataMap.put("param", "hello");
manager.addCronJob("job2", "group1", "0 0 12 * * ?",
MyJob.class, dataMap);
}
}
通用CRUD定时任务框架
提供完整的增删改查功能:
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 可管理的定时任务
*/
public class ManageableTimerTask {
private final String taskId;
private final Runnable task;
private final CronExpression cronExpression;
private ScheduledFuture<?> future;
private volatile boolean running = false;
public ManageableTimerTask(String taskId, Runnable task, String cronExpression) {
this.taskId = taskId;
this.task = task;
this.cronExpression = new CronExpression(cronExpression);
}
// getters and setters...
}
/**
* 定时任务管理器(支持CRUD)
*/
public class TaskManager {
private final ScheduledExecutorService scheduler;
private final ConcurrentHashMap<String, ManageableTimerTask> tasks;
private final ConcurrentHashMap<String, ScheduledFuture<?>> futures;
public TaskManager() {
this.scheduler = Executors.newScheduledThreadPool(10);
this.tasks = new ConcurrentHashMap<>();
this.futures = new ConcurrentHashMap<>();
}
/**
* 创建新任务
*/
public boolean createTask(String taskId, Runnable task, String cronExpression) {
if (tasks.containsKey(taskId)) {
return false;
}
ManageableTimerTask timerTask = new ManageableTimerTask(taskId, task, cronExpression);
tasks.put(taskId, timerTask);
return true;
}
/**
* 启动任务
*/
public boolean startTask(String taskId) {
ManageableTimerTask timerTask = tasks.get(taskId);
if (timerTask == null || futures.containsKey(taskId)) {
return false;
}
ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(
timerTask.getTask(),
0,
timerTask.getCronExpression().getIntervalSeconds(),
TimeUnit.SECONDS
);
futures.put(taskId, future);
return true;
}
/**
* 停止任务
*/
public boolean stopTask(String taskId) {
ScheduledFuture<?> future = futures.remove(taskId);
if (future != null) {
future.cancel(false);
return true;
}
return false;
}
/**
* 更新任务
*/
public boolean updateTask(String taskId, Runnable task, String cronExpression) {
stopTask(taskId);
createTask(taskId, task, cronExpression);
startTask(taskId);
return true;
}
/**
* 删除任务
*/
public boolean deleteTask(String taskId) {
stopTask(taskId);
tasks.remove(taskId);
return true;
}
/**
* 获取所有运行中的任务
*/
public List<String> getRunningTasks() {
return new ArrayList<>(futures.keySet());
}
/**
* 获取所有注册的任务
*/
public Map<String, ManageableTimerTask> getAllTasks() {
return new HashMap<>(tasks);
}
}
Spring Boot 集成方案
使用 Spring 的 @Scheduled 注解:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@EnableScheduling
public class SpringScheduledTasks {
// 每5秒执行一次
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("现在时间: " + LocalDateTime.now());
}
// 固定延迟(任务完成后3秒)
@Scheduled(fixedDelay = 3000)
public void processData() throws InterruptedException {
System.out.println("开始处理数据...");
Thread.sleep(2000); // 模拟处理时间
System.out.println("数据处理完成");
}
// Cron表达式(每天中午12点)
@Scheduled(cron = "0 0 12 * * ?")
public void dailyReport() {
System.out.println("生成每日报告");
}
// 首次延迟1秒,然后每2秒执行
@Scheduled(initialDelay = 1000, fixedRate = 2000)
public void delayedTask() {
System.out.println("延迟后开始执行");
}
}
选择建议
- 简单场景:使用
ScheduledExecutorService - 企业级应用:使用 Quartz
- Spring Boot项目:使用
@Scheduled - 需要可视化管理:使用 Quartz + 管理界面
这样你可以根据具体需求选择合适的定时模块方案!