springboot application.yaml 配置定时任务学习记录

思路

  1. 在 .yaml 或 .properties中配置定时任务 cron 表达式
  2. 建一个定时任务配置读取类,读取 .properties 中的配置表达式
  3. 写自己的定时任务类,实现Runnable 接口
  4. 建一个定时任务调度类(类名随意:ScheduledTasks.java ),负责调度所有的任务
  5. 从Application启动任务调度

具体实现

1、新建 taskcommon.properties中配置定时任务 cron 表达式

#### 定时任务
#每月1号每月1号凌晨1点执行一次  统计上一个月的缴费
job.taskCronMap[costCountCron] = 0 */5 * * * ?

2、新建 TaskPropertiesConfig.ava , 用来读取定时任务的表达式

  • ConfigurationProperties(prefix = “job”) 配置的是配置文件里前缀为job 的配置属性
  • PropertySource(“classpath:datapro/taskcommon.properties”) 配置读取文件的路径,classpath标识项目中静态资源的根目录,例如 我的配置文件存放路径目录 :huohuang\apartmanagement\src\main\resources\datapro
  • taskCronMap 与配置文件中配置的属性名对应,读取时才能赋值。
package com.qianlong.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author: 
 * @Date:
 * @Description:
 */
@Component
@ConfigurationProperties(prefix = "job")
@PropertySource("classpath:datapro/taskcommon.properties")
public class TaskPropertiesConfig {
    /**
     * 定时任务的cron 表达式集合
     */
    private Map<String, String> taskCronMap;

    public Map<String, String> getTaskCronMap() {
        return taskCronMap;
    }

    public void setTaskCronMap(Map<String, String> taskCronMap) {
        this.taskCronMap = taskCronMap;
    }
}

3、新建定时任务类 CostCountJob,java ,并实现Runnable 接口。

  • @PostConstruct 该任务在项目启动时先立即执行一次。
package com.qianlong.job;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author: 
 * @Date: 
 * @Description:
 */
@Component
public class CostCountJob implements Runnable {
    @Override
    @PostConstruct
    public void run() {
        System.out.println( "定时任务启动" );
    }
}

4、新建任务调度类 ScheduledTasks.java ,所有的任务调度都由该类调度。

package com.qianlong.job;
import com.qianlong.config.TaskPropertiesConfig;
import org.apache.commons.lang.StringUtils;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author: 
 * @Date: 
 * @Description: 定时任务调度类
 */
@Component
public class ScheduledTasks {
    @Autowired
    private TaskScheduler taskScheduler;
    @Autowired
    private TaskPropertiesConfig tascConfig;
    @Autowired
    private CostCountJob costCountJob;
    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    public void scheduleAllCrons() {
        Map<String, String> taskCronMap = tascConfig.getTaskCronMap();
        // 配置文件taskcommon.properties 中配置了 costCountCron 的corn表达式,定时任务costCountJob才启动
        if(taskCronMap!=null && taskCronMap.size()>0){
            String corn = taskCronMap.get("costCountCron");
            if(StringUtils.isNotEmpty(corn)){
                taskScheduler.schedule(costCountJob, new CronTrigger(corn));
            }
        }
    }
}

5、springboot启动类MainApplication 中启动任务调度。

package com;
import com.qianlong.job.ScheduledTasks;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author: Administrator
 * @Date: 2021/4/17 13:32
 * @Description:
 */
@EnableTransactionManagement
@SpringBootApplication
@MapperScan("com.qianlong.mapper")
public class ProMainApplication {
    @Bean
    public TaskScheduler taskScheduler() {
        return new ConcurrentTaskScheduler();
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext app =SpringApplication.run(ProMainApplication.class,args);
        System.out.println( "启动成功");
        //定时任务调度启动
        ScheduledTasks scheduledTasks = app.getBean(ScheduledTasks.class);
        scheduledTasks.scheduleAllCrons();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 中,可以使用 YAMLYAML Ain't Markup Language)文件来配置定时任务YAML 是一种人类友好的数据序列化格式,它可以用来替代传统的 XML 或 Properties 文件,更加简洁和易读。 使用 YAML 文件配置定时任务可以实现以下作用: 1. 配置定时任务的触发时间和执行逻辑:通过 YAML 文件可以指定定时任务的触发时间表达式Cron 表达式)和执行的具体逻辑。这样,可以方便地在应用程序中定义和管理多个定时任务。 2. 避免硬编码:将定时任务配置信息从源代码中分离出来,以便于灵活地修改和调整。通过 YAML 文件,可以在不重新编译和部署应用程序的情况下更改定时任务配置。 3. 统一管理配置信息:将所有的定时任务配置信息集中在一个 YAML 文件中,可以方便地进行统一管理和维护。这样,可以减少重复劳动和错误,并提高配置的可读性和可维护性。 使用 YAML 文件配置定时任务的步骤如下: 1. 在 Spring Boot 项目的 resources 目录下创建一个名为 application.yml 或 application.yamlYAML 文件。 2. 在 YAML 文件中使用 cron 表达式配置定时任务的触发时间,例如: ```yaml spring: task: scheduling: cron: expression: "0 0 * * * ?" # 每天凌晨执行一次 ``` 3. 在应用程序中添加 @EnableScheduling 注解来启用定时任务的支持。 4. 在需要执行定时任务的方法上添加 @Scheduled 注解,并根据需要指定触发时间和执行逻辑。例如: ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyTask { @Scheduled(cron = "0 0 * * * ?") // 每天凌晨执行一次 public void doTask() { // 执行定时任务的逻辑 System.out.println("定时任务执行了!"); } } ``` 通过以上步骤,就可以使用 YAML 文件配置定时任务,并在 Spring Boot 应用程序中实现定时任务的自动触发和执行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值