【本文将介绍两种定时器使用方式】 方式一:非常简便的定时器使用,Spring框架自带定时器 步骤1:在主启动类上开启定时器 @SpringBootApplication @EnableScheduling public class QuartzTestApplication { public static void main(String[] args) { SpringApplication.run(QuartzTestApplication.class, args); } } 步骤2:书写定时任务类 package com.offcn.quartztest; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; //需要将该任务类添加到容器中 @Component public class QuartzTask { //每隔1分钟执行1次 @Scheduled(cron = "0 0/1 * * * *") public void quartzTask(){ System.out.println("定时任务:"+new Date()); } } 方式二:分工明确的定时器 步骤一:添加定时器依赖 <!--定时器的依赖--> <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> 步骤二:主启动类上开启定时任务 @SpringBootApplication @EnableScheduling public class QuartzTestApplication { public static void main(String[] args) { SpringApplication.run(QuartzTestApplication.class, args); } } 步骤三:编写任务类 package com.offcn.job; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; @Component public class ImportJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) { System.out.println("任务"); } @Scheduled(cron = " * * * * * *") public void importData(){ System.out.println(new Date()+":任务"); } } 步骤四:编写触发器 package com.offcn.quart; import com.offcn.work.ImportJob; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import java.util.Date; //创建调度类 public class WorkQuart { public static void main(String[] args) throws InterruptedException, SchedulerException { Scheduler scheduler = getScheduler(); scheduler.scheduleJob(getJobDetail() , getTrigger()); } //创建工作细节 public static JobDetail getJobDetail(){ // job 唯一标识 test.test-1 JobKey jobKey = new JobKey("importJob" , "job-1"); // 创建工作细节 JobDetail jobDetail = JobBuilder.newJob(ImportJob.class).withIdentity(jobKey).build(); return jobDetail; } //创建一个调度器 public static Scheduler getScheduler() throws SchedulerException { Scheduler scheduler = new StdSchedulerFactory().getScheduler(); // 开启调度器 scheduler.start(); return scheduler; } //创建一个触发器 public static Trigger getTrigger(){ Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger-1" , "job-1") // 延迟一秒执行 .startAt(new Date(System.currentTimeMillis() + 1000)) // 每隔一秒执行 并一直重复 .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever()).build(); return trigger; } }
10-31
919