【Spring Boot】定時任務spring
測試用業務Serviceide
package com.example.schedule.service; import org.springframework.stereotype.Service; @Service public class UserService { public void syncUserData(){ System.out.println("syncUserData"); } } package com.example.schedule.service; import org.springframework.stereotype.Service; @Service public class StudentService { public void syncStudentData(){ System.out.println("syncStudentData"); } }
一、使用Spring的@Scheduled註解spring-boot
使用@EnableScheduling註解啓用Spring定時任務測試
package com.example.schedule; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class ScheduleApplication { public static void main(String[] args) { SpringApplication.run(ScheduleApplication.class, args); } }
定時方法spa
package com.example.schedule.scheduled_bean; import com.example.schedule.service.StudentService; import com.example.schedule.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class YcxScheduledBean { @Autowired UserService userService; @Autowired StudentService studentService; @Scheduled(cron="*/2 * * * * ?") public void syncData() { System.out.println(">>> YcxScheduledBean"); userService.syncUserData(); studentService.syncStudentData(); } }
二、使用quartzcode
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
繼承QuartzJobBeanblog
package com.example.schedule.job; import com.example.schedule.service.StudentService; import com.example.schedule.service.UserService; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.QuartzJobBean; public class YcxSyncJob extends QuartzJobBean { @Autowired UserService userService; @Autowired StudentService studentService; @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { System.out.println(">>> QuartzJobBean 同步任務"); userService.syncUserData(); studentService.syncStudentData(); } }