使用定时任务 随着项目启动定时执行
有关定时任务的使用
<!--引入quartz定时框架--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
1、 spring中使用两个注解 实现定时任务的实现
(1)在启动类开启定时任务@EnableScheduling
@SpringBootApplication //开启定时任务 @EnableScheduling public class Application{ public static void main(String[] args) { SpringApplication.run(Application.class, args); } } (2)@Scheduled(cron = " ")来指定自动执行规则 /** * 每分钟执行一次 */ @Scheduled(cron = "0 0/1 * * * ?") public void init() { log.info("定时任务执行开始"); //业务方法逻辑... log.info("定时任务执行结束"); }
(2)有关quartz实现定时任务
public class MyJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sdf.format(new Date()); System.out.println("当前时间-format:time="+format); } } public class MyScheduler { public static void getMyScheduler() throws SchedulerException { //创建schedule 调度器 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); //创建jobbuilder JobDetail jobDetail = (JobDetail) JobBuilder.newJob(MyJob.class) .withIdentity("nala","jobDetailGroup") .withDescription("使用Cron") .build(); //创建TriggerBuilder 触发器 设置触发时间 3天一次 CronTrigger trigger = TriggerBuilder.newTrigger() .withIdentity("nala", "tiggerGroup") .withDescription("使用cron设置调度时间") .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 */3 * ? ")) .build(); //关联 scheduler.scheduleJob(jobDetail,trigger); if(!scheduler.isShutdown()){ scheduler.start(); } //执行 scheduler.start(); //一直不关闭schedule 就会一直运行 while (true){ } } @Test public void test() throws SchedulerException { getMyScheduler(); } }
(3) Spring Boot集成Quartz实现定时任务
//创建自定义job public class MyJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sdf.format(new Date()); System.out.println("jobExecutionContext"+format); } } /** * @Date 2021/10/22 14:36 */ @Configuration @DisallowConcurrentExecution public class QuartzConfig { @Bean public JobDetail getJobDetail() { return JobBuilder.newJob(MyJob.class) .withIdentity("jobDetail","jobDetailGroup") .withDescription("使用cron") .storeDurably() .build(); } @Bean public Trigger getTrigger() { //cron方式,每隔3天执行一次 return TriggerBuilder.newTrigger().forJob(getJobDetail()) .withIdentity("trigger","triggerGroup") .withDescription("使用Cron表达式") .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 */3 * ?")) .build(); } }