使用SpringBoot设置定时任务

版权声明:转载记得宣传奥~。~ https://blog.csdn.net/c_ym_ww/article/details/86152799

使用Quartz设置定时任务

        maven依赖
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-quartz -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

需要一个执行任务的执行类

public class TestQuartzJob extends QuartzJobBean {
    private final static Logger LOGGER = LoggerFactory.getLogger(TestQuartzJob.class);

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        LOGGER.info("Test QuartzJob");
    }
}

需要一个定时任务的配置类

@Configuration
public class QuartzConfiguration {
    @Bean
    public JobDetail testQuartzJobDetail() {
        return JobBuilder.newJob(TestQuartzJob.class).withIdentity("自定义名称").storeDurably().build();
    }

    @Bean
    public Trigger testQuartzTrigger() {
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever();
        return TriggerBuilder.newTrigger()
                .forJob(testQuartzJobDetail()).withIdentity("自定义名称")
                .withSchedule(scheduleBuilder).build();
    }
}

效果图:

 

 

通过注解来设置每日定时任务

@Configuration
@EnableScheduling
public class TestJob{
    private final Logger logger = LoggerFactory.getLogger(TestJob.class);

    /**
     * cron表达式
     */
    @Scheduled(cron = "0 0 9 * * ?")
    public void test() {
        logger.info("测试定时任务");
    }

 

这2种定时任务各有优劣,一般每天的数据统计可以用第二种简单粗暴,一般实时数据采集然后存入缓存减少响应时间则推荐第一种。

猜你喜欢

转载自blog.csdn.net/c_ym_ww/article/details/86152799