springboot实现定时任务的两种方式

时间:2022-03-18 07:53:02

 方式一:在springboot启动类上添加@EnableScheduling注解,然后创建具体的任务类,在方法上添加@Scheduled注解,并指明执行频率即可。如下:

@Component
public class TestJob {

private final Logger logger = LoggerFactory.getLogger(TestJob.class);

@Scheduled(cron = "*/3 * * * * *")
public void testJob() {
logger.info("Job Test...");
}
}

方式二:创建一个继承了QuartzJobBean的任务类,同时创建quarz配置类,以向spring容器中注入JobDetail和Trigger。如下:
public class Test2Job extends QuartzJobBean {

private final Logger logger = LoggerFactory.getLogger(Test2Job.class);
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
logger.info("Test2 Job...");
}
}
@Configuration
public class ScheculerConfiguration {

@Bean
public JobDetail jobDetail() {
return JobBuilder.newJob(Test2Job.class)
.withIdentity("test2Job")
.storeDurably()
.build();
}

@Bean
public Trigger jobTrigger() {
ScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInMilliseconds(3)
.repeatForever();
return TriggerBuilder.newTrigger()
.withIdentity("test2JobTrigger")
.forJob(jobDetail())
.withSchedule(scheduleBuilder)
.build();
}
}