方法1、使用Timer和TimerTask类
Timer和TimerTask是java.util包下的类,用于实现定时任务
- 1)创建TimerTask定时器任务,可以通过匿名内部类的方式创建
- 2)创建Timer定时器,调用定时器的方法执行定时器任务
Timer的两个方法schedule()和scheduleAtFixedRate()及其重载方法:
- void schedule(TimerTask task, long delay):在指定时间后执行1次任务,其中delay表示时延,单位是毫秒,设置为1000,则表示1秒后执行一次定时器任务;
- void schedule(TimerTask task, long delay, long period):指定延迟指定时间后周期性地执行任务(delay毫秒后,每period毫秒执行一次)
- void scheduleAtFixedRate(TimerTask task, long delay, long period):指定延迟指定时间后周期性地执行任务(delay毫秒后,每period毫秒执行一次)
- void scheduleAtFixedRate(TimerTask task, Date firstTime,long period) :从指定日期firstTime开始,每period毫秒执行一次任务
案例代码:
public class TimerExample {
public static void main(String[] args) {
// 创建定时器
Timer timer = new Timer();
// 创建定时器任务
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("Hello world!");
}
};
timer.schedule(timerTask, 1000); // 1秒后执行一次
timer.schedule(timerTask, 2000, 2000); // 两秒后每两秒执行一次
timer.scheduleAtFixedRate(timerTask, 5000, 5000); // 5秒后每5秒执行一次
timer.scheduleAtFixedRate(task, new Date(), 6000); // 每6秒执行一次
}
}
方法2、使用线程池
其中线程池的方法使用和Timer一样,TimeUnit是一个枚举类型,用于指定时间单位。
案例代码:
public class TimerExample {
public static void main(String[] args) {
// 创建定时器任务
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("Hello world!");
}
};
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
scheduledThreadPool.schedule(timerTask, 1000, TimeUnit.MILLISECONDS);
scheduledThreadPool.scheduleAtFixedRate(timerTask, 1000, 1000, TimeUnit.MILLISECONDS);
}
}
方法3、使用Spring框架的@Scheduled注解
- 1)在springBoot启动类上添加@EnableScheduling注解
@EnableScheduling
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
- 2)创建一个定时任务类的bean,在类的方法上使用@Scheduled注解,通过注解的cron属性设置定时器的属性。
@Component
public class TimerTask {
@Scheduled(cron = "0 5 1 16 3 *")
public void task() {
System.out.println("定时任务...");
}
}
以上代码指定在2024年3月16日01:05:00执行一次定时任务。
方法4、通过Quartz任务调度工具
- 1)在pom.xml中添加quartz的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- 2)创建quartz的配置类
@Configuration
public class QuartzConfig {
// 定义的Bean对象
@Bean
public JobDetail jobDetail(){
System.out.println("showTime方法运行");
return JobBuilder.newJob(QuartzJob.class) // 绑定要运行的任务类的类对象
.withIdentity("job") // 设置job的名称
.storeDurably() // 信息持久
.build();
}
// 声明触发器,触发器决定我们的工作\任务何时触发
@Bean
public Trigger trigger(){
System.out.println("showTime触发器运行");
// 定义Cron表达式,每分钟触发一次
CronScheduleBuilder cronScheduleBuilder =
CronScheduleBuilder.cronSchedule("0/10 * * * * ?");
return TriggerBuilder.newTrigger()
.forJob(jobDetail()) // 绑定JobDetail对象
.withIdentity("trigger") // 定义触发器名称
.withSchedule(cronScheduleBuilder) // 绑定Cron表达式
.build();
}
}
- 3)定义Job
public class QuartzJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) {
// 输出当前时间
System.out.println(LocalDateTime.now());
}
}
总结:
Java中实现定时器的常见方式有三种。具体如下:
- 使用Timer类。Timer类允许你调度一个TimerTask任务,可以让程序按照某一个频度执行,但不能在指定时间运行。
- 使用ScheduledExecutorService接口。这个接口允许你调度一个任务在未来的某个时间点执行,或者按照一定的时间间隔重复执行。
- 使用Quartz框架。Quartz是一个功能强大的开源定时任务调度框架,可以支持复杂的调度需求,如按照特定的时间表执行任务,支持任务的持久化存储等。
此外,还可以使用Spring框架的@Scheduled注解或者Quartz框架的@PersistJobDataAfterExecution注解来实现定时任务。