springboot 集成的定时任务及quartz定时器 及动态配置定时时间

springboot自己集成的定时任务

  1. 在启动类上添加 @EnableScheduling // springboot 自己的定时任务
  2. 写一个定时类
@Component 
public class TestJob {

    @Scheduled(cron = "0/2 * * * * *")  // 2秒执行一次
    public void job(){
        System.out.println("springboot - EnableScheduling ");
    }
}

springboot 集成quartz定时器

  1. pom.xml 添加quartz依赖
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
  1. application.properties配置文件(线程池的基本大小、数据库最大连接池、线程并发数)
corePoolSize=10
maxPoolSize=200
queueCapacity=10
  1. 添加定时类
@DisallowConcurrentExecution
public class TestQuartz extends QuartzJobBean{

    /**
     * 执行定时任务
     * @param context
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        System.out.println("quartz定时任务");
    }
}
  1. springboot 可以配置一个通过线程池异步优化,可以启用多线程的方式来执行了,更加高效
@Configuration
@EnableAsync
public class AsyncConfig {

    @Value("${corePoolSize}")
    private int  corePoolSize;

    @Value("${maxPoolSize}")
    private int maxPoolSize;

    @Value("${queueCapacity}")
    private int queueCapacity;

    @Bean
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        return executor;
    }
}
  1. 结合quartz框架做一些配置
@Configuration
public class TestQuartzConfig {

    @Bean
    public JobDetail testQuartzDetail(){
        return JobBuilder.newJob(TestQuartz.class)
                .withIdentity("zxf").storeDurably()
                .requestRecovery(true).build();
    }


    @Bean
    public Trigger testQuartzTrigger(){
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("name","zxf");

        SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder
                .simpleSchedule()
                .withIntervalInSeconds(2) //设置时间周期单位秒
                .repeatForever();
        return TriggerBuilder.newTrigger().forJob(testQuartzDetail())
                .withIdentity("zxf")
                .withSchedule(simpleScheduleBuilder)
                .usingJobData(jobDataMap)
                .build();
    }
}

启动后效果如图:
在这里插入图片描述

动态配置时间设置

  1. @PropertySource(“classpath:application-test.properties”)在类上添加你对应的配置文件地址
  2. @Scheduled(cron={aaa.bbb}) 配置文件里设置定时时间 设置你配置的指定名称
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值