복붙노트

[SPRING] 스프링 부트는 새로운 스케줄 작업을 동적으로 추가합니다.

SPRING

스프링 부트는 새로운 스케줄 작업을 동적으로 추가합니다.

나는 스프링 부트 애플리케이션을 작성 중이다.

내 요구 사항은 - 리소스 (src / main / resources) 폴더에 새 xml 파일을 추가하면 해당 파일을 읽고 각각에서 일부 URL 및 기타 특정 설정을 가져와야합니다. 그리고 그 URL을 매일 매일 데이터를 다운로드해야합니다. 그래서 새로운 스케줄러 작업은 URL과 일부 설정으로 시작됩니다

새 작업은 xml 파일에있는 cron 표현식을 사용하는 다른 스케줄 시간에 실행됩니다 또한 파일은 언제든지 동적으로 추가됩니다. 그것을 삽입하는 법.

해결법

  1. ==============================

    1.작업을 동적으로 예약하려는 경우 ExecutorService, 특히 ScheduledThreadPoolExecutor를 사용하여 작업을 수행 할 수 있습니다.

    작업을 동적으로 예약하려는 경우 ExecutorService, 특히 ScheduledThreadPoolExecutor를 사용하여 작업을 수행 할 수 있습니다.

    Runnable task  = () -> doSomething();
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
    // Schedule a task that will be executed in 120 sec
    executor.schedule(task, 120, TimeUnit.SECONDS);
    
    // Schedule a task that will be first run in 120 sec and each 120sec
    // If an exception occurs then it's task executions are canceled.
    executor.scheduleAtFixedRate(task, 120, 120, TimeUnit.SECONDS);
    
    // Schedule a task that will be first run in 120 sec and each 120sec after the last execution
    // If an exception occurs then it's task executions are canceled.
    executor.scheduleWithFixedDelay(task, 120, 120, TimeUnit.SECONDS);
    

    봄에는 Task and Scheduling API에 의존 할 수 있습니다.

    public class MyBean {
    
        private final TaskScheduler executor;
    
        @Autowired
        public MyBean(TaskScheduler taskExecutor) {
            this.executor = taskExecutor;
        }
    
        public void scheduling(final Runnable task) {
            // Schedule a task to run once at the given date (here in 1minute)
            executor.schedule(task, Date.from(LocalDateTime.now().plusMinutes(1)
                .atZone(ZoneId.systemDefault()).toInstant()));
    
            // Schedule a task that will run as soon as possible and every 1000ms
            executor.scheduleAtFixedRate(task, 1000);
    
            // Schedule a task that will first run at the given date and every 1000ms
            executor.scheduleAtFixedRate(task, Date.from(LocalDateTime.now().plusMinutes(1)
                .atZone(ZoneId.systemDefault()).toInstant()), 1000);
    
            // Schedule a task that will run as soon as possible and every 1000ms after the previous completion
            executor.scheduleWithFixedDelay(task, 1000);
    
            // Schedule a task that will run as soon as possible and every 1000ms after the previous completion
            executor.scheduleWithFixedDelay(task, Date.from(LocalDateTime.now().plusMinutes(1)
                .atZone(ZoneId.systemDefault()).toInstant()), 1000);
    
            // Schedule a task with the given cron expression
            executor.schedule(task, new CronTrigger("*/5 * * * * MON-FRI"));
        }
    }
    

    그리고 트리거를 구현하여 자신 만의 트리거를 제공 할 수 있습니다.

    구성 클래스에서 @EnableScheduling을 사용하여 스케줄링을 활성화하는 것을 잊지 마십시오.

    디렉토리 내용 청취에 관해서는 WatchService를 사용할 수 있습니다. 같은 것 :

    final Path myDir = Paths.get("my/directory/i/want/to/monitor");
    final WatchService watchService = FileSystems.getDefault().newWatchService();
    // listen to create event in the directory
    myDir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
    // Infinite loop don't forget to run this in a Thread
    for(;;) {
       final WatchKey key = watchService.take();
       for (WatchEvent<?> event : key.pollEvents()) {
           WatchEvent<Path> watchEvent = (WatchEvent<Path>) event;
           Path newFilePath = myDir.resolve(watchEvent.context());
           //do something with the newFilePath
        }
        // To keep receiving event
        key.reset();
    }
    

    자세한 내용은이 문서의 "변경 사항에 대한 디렉토리보기"를 참조하십시오.

  2. ==============================

    2.당신은 봄 주석을 통해 그것을 할 수 있습니다 :

    당신은 봄 주석을 통해 그것을 할 수 있습니다 :

    @Scheduled(fixedRate = 360000)
    public void parseXmlFile() {
        // logic for parsing the XML file.
    }
    

    이 방법은 무효가되어야합니다. 또한 주 수업에서 일정을 사용하도록 설정해야합니다.

    @SpringBootApplication
    @EnableScheduling
    public class Application {
    
        public static void main(String[] args) throws Exception {
            SpringApplication.run(Application.class);
        }
    }
    

    자세한 내용은 다음을 참조하십시오. https://spring.io/guides/gs/scheduling-tasks/

  3. ==============================

    3.외부 동적 매개 변수 구성, 실시간 모니터링이 라이브러리를 사용해보십시오.

    외부 동적 매개 변수 구성, 실시간 모니터링이 라이브러리를 사용해보십시오.

    https://github.com/tyrion9/mtask

    mtasks.yml의 구성 매개 변수

    -   code: complex
        scheduled:
            period: 1000
        name: Autowired Param MTask
        className: sample.sample2.ComplexMTask
        params:
            name: HoaiPN
        autoStart: true
    

    동적 매개 변수 구성 :

    curl -X GET http://localhost:8080/api
    
    curl -X POST http://localhost:8080/api/helloworld/stop
    
    curl -X POST http://localhost:8080/api/helloworld/start
    
  4. from https://stackoverflow.com/questions/46974272/spring-boot-add-new-schedule-job-dynamically by cc-by-sa and MIT license