整理不易,不喜勿喷。谢谢

SpringBoot — 整合Ldap.
SpringBoot — 整合Spring Data JPA.
SpringBoot — 整合Elasticsearch.
SpringBoot — 整合spring-data-jpa和spring-data-elasticsearch.
SpringBoot — 整合thymeleaf.
SpringBoot — 注入第三方jar包.
SpringBoot — 整合Redis.
Springboot — 整合slf4j打印日志.
Springboot — 整合定时任务,自动执行方法.
Springboot — 配置多数据源,使用JdbcTemplate以及NamedParameterJdbcTemplate.
Sprignboot — 详解pom.xml中build和profile.
SpringBoot — 监控.
SpringBoot — 缓存Cache/Redis.
SpringBoot与Zookeeper.
Git的使用.

1.定时任务

1.1@Schedule

在方法上直接使用

@Scheduled(cron = "0 0/2 * * * ?")
public void runScheduleTask(){
@SpringBootApplication
@EnableScheduling
public class xxxxxApplication {

	public static void main(String[] args) {
		SpringApplication.run(xxxxxApplication.class, args);
	}

}

1.2使用配置文件,设定cron

简单的配置类

application.properties

spring.exe-IS-cron=0 */2 *  * * ?
spring.exe-User-cron=0 */10 * * * ?

配置类

@Data
@Configuration
@ConfigurationProperties( prefix = "spring")
public class xxxxProperties {
    private String exeIsCron;
    private String exeUserCron;
}

下面是复杂一点的配置类

application.properties

#schedule task
spring:
  tasks:
  - scheduleTaskName: Relationship     #任务名称
    valid: true                        #是否开启定时任务
    cron: 0 0 12 * * ?                 #任务表达式
    #cron: 0/5 * * * * ?
  - scheduleTaskName: unknow           #任务名称
    valid: false                       #是否开启定时任务
    cron: 0/5 * * * * ?                #任务表达式

配置类

//接收的实体类
@Data
public class Task {
    private String scheduleTaskName;
    private Boolean valid;
    private String cron;
}

//配置类
@Data
@Configuration
@ConfigurationProperties(prefix = "spring")
public class ScheduleConfig {

    List<Task> tasks;
}

//上面这种配置,在执行是要选择对应的schedule。使用stream流
Task relationship = scheduleConfig.getTasks().stream().filter(name -> name.getScheduleTaskName().equals("Relationship")).findFirst().get();
String exeCron = relationship.getCron();

启动类

@SpringBootApplication
@EnableScheduling
public class xxxxxApplication {

	public static void main(String[] args) {
		SpringApplication.run(xxxxxApplication.class, args);
	}

}

service

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Slf4j
@Service
public class CronJobService implements SchedulingConfigurer {

    private static final String DEFAULT_CRON = "0/5 * * * * ?";
    private String cron = DEFAULT_CRON;

    @Autowired
    private xxxxxProperties xxxxxProperties;
    @Autowired
    private InfluxService influxService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> {

            influxService.insertToInflux();
            influxService.allMsgToInflux();
            System.out.println("first cron execute,insert allSystemMsg,linkages,terms");
        }, (triggerContext) -> {
            String exeCron = dataGovProperties.getExeIsCron();
            if (!StringUtils.isEmpty(exeCron)) {
                cron = exeCron;
            }
            CronTrigger trigger = new CronTrigger(cron);
            Date nextExecDate = trigger.nextExecutionTime(triggerContext);
            log.debug("at 23:00 every day, query information steward");
            return nextExecDate;
        });

        taskRegistrar.addTriggerTask(() -> {
            influxService.userMsgToInflux();
            System.out.println("second cron execute,insert user");
        },(triggerContext)->{
            String exeCron = dataGovProperties.getExeUserCron();
            if (!StringUtils.isEmpty(exeCron)) {
                cron = exeCron;
            }
            CronTrigger trigger = new CronTrigger(cron);
            Date nextExecDate = trigger.nextExecutionTime(triggerContext);
            log.debug("Every 10 minutes, query user msg");
            return nextExecDate;
        });
    }

    public void setCron(String cron) {
        System.out.println("当前cron="+this.cron+"->将被改变为:"+cron);
        this.cron = cron;
    }

}

2.@Autowired

此方法必须要有参数,注入的时候会调用一次该方法,做一些初始化操作

@Autowired
public void checkDate(int a){
	xxxxxx
}

3.使用ApplicationRunner

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class MyRunner implements ApplicationRunner {

    @Autowired
    private CheckDataController checkDataController;
    @Autowired
    private ConfigurableApplicationContext context;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
       checkDataController.checkDataChange();
       System.out.println("automatically turn off tomcat ");
       //自动关闭Tomcat
       context.close();
    }
}

4.使用CommandLineRunner

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class MyRunner implements CommandLineRunner {

    @Autowired
    private CheckDataController checkDataController;
    @Autowired
    private ConfigurableApplicationContext context;
    
    @Override
    public void run(String... args) {
       checkDataController.checkDataChange();
       System.out.println("automatically turn off tomcat");
       //自动关闭Tomcat
       context.close();
    }
}
其实第三个和第四个方法差别不大,就是参数不一样
如果有多个的话,用@Order进行排序,值越小越先执行
@Component
@Order(1)
public class MyRun1 implements CommandLineRunner {
    xxxxxx
  }
  
@Component
@Order(2)
public class MyRun2 implements CommandLineRunner {
    xxxxxx
  }

5.Web项目自动关闭

上面已经使用的ConfigurableApplicationContext就是啦

    @Autowired
    private ConfigurableApplicationContext context;
    
    在方法中直接使用 ,如上
    context.close();

注意事项: 使用ConfigurableApplicationContext的时候Debug要小心.

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐