java 如何定时执行
定时执行的方法
在Java中,实现定时执行任务可以通过多种方式完成,以下是几种常见的方法:
使用 java.util.Timer 和 TimerTask
Timer 和 TimerTask 是Java提供的一个简单的定时任务调度工具。

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());
}
};
// 延迟1秒后执行,之后每隔2秒执行一次
timer.schedule(task, 1000, 2000);
}
}
使用 ScheduledExecutorService
ScheduledExecutorService 是更现代且灵活的定时任务调度工具,推荐使用。
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorExample {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> System.out.println("Task executed at: " + System.currentTimeMillis());
// 延迟1秒后执行,之后每隔2秒执行一次
executor.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS);
}
}
使用 Spring 的 @Scheduled 注解
如果项目基于Spring框架,可以使用 @Scheduled 注解简化定时任务的配置。

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTask {
@Scheduled(fixedRate = 2000)
public void executeTask() {
System.out.println("Task executed at: " + System.currentTimeMillis());
}
}
需要在Spring配置类中启用定时任务支持:
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class AppConfig {
}
使用 Quartz 调度框架
对于复杂的调度需求,Quartz是一个功能强大的调度框架。
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzExample {
public static void main(String[] args) throws SchedulerException {
JobDetail job = JobBuilder.newJob(MyJob.class)
.withIdentity("myJob", "group1")
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(2)
.repeatForever())
.build();
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(job, trigger);
scheduler.start();
}
public static class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) {
System.out.println("Job executed at: " + System.currentTimeMillis());
}
}
}
选择建议
- 简单任务:
Timer或ScheduledExecutorService。 - Spring项目:
@Scheduled注解。 - 复杂调度需求:Quartz框架。






