How to @ Scheduled Read Dynamic Configuration Files

  • 2021-09-12 01:24:07
  • OfStack

@ Scheduled reading dynamic configuration files

Configuration information for application. yml configuration file



agreeAccTask:
#
#  Every 3 Execute in minutes 1 Times, handTime: 0 0/3 * * * ?     Every night 2 Point  handTime: 0 0 2 * * ?
#   Specify a few days : day 1  Indicates that within the current day, 2 Denote 2 Within days, and so on 
#   Specify the strength of the generated directory : dir F:/agreeacc
 time: 0 0 2 * * ?
 day: 1
 dir: F:/agreeacc3

java backend


 * @Description: Alipay withholding reconciliation files are generated regularly 
 */
@Slf4j
@Component
@EnableScheduling
public class AgreeAccTask {
    @Autowired
    private AgreeAccMapper agreeAccMapper;
    @Value("${agreeAccTask.day}")
    private String day;
    @Value("${agreeAccTask.dir}")
    private String dir;
    @Scheduled(cron="${agreeAccTask.time}")
    public void AgreeAccTask(){
        String today=DateUtil.date2String(new Date(),DateUtil.PATTERN_DATE);
        log.info(" Start of generation of withholding reconciliation file Date :"+today);
        int j=Integer.parseInt(day);

SpringBoot @ Scheduled Read configuration file for cron value

1. Add annotation @ Component to the class and hand it over to Spring for management

2. Specify the configuration file name in @ PropertySource, as follows: Specify the application. properties file in the src/main/resource directory

3. The reference content of configuration file application. properties is as follows


# Execute per second 1 Times 
cron=0/1 * * * * *

import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:/application.properties")
public class ScoreTask1 {
 
 @Scheduled(cron="${cron}")
 public void scoreTask(){
  System.out.println(" Read from configuration file cron Expression timer ");
 }
}

Step 1 derivation can isolate the development environment from the production environment cron expression, so that the system automatically executes the configuration file cron expression every time it is packaged and deployed, thus reducing the number of manual code modifications.

Here we recommend a tool for online generation of cron expressions online Cron expression builder

https://cron.qqe2.com/

Note that the cron expression can only be configured with 6-bit parameters, that is, seconds, minutes, days, months and weeks. Sometimes the generator will generate 7-bit parameters, so that errors will be reported when the java code is executed


Related articles: