web-dev-qa-db-ja.com

Spring Bootは新しいスケジュールジョブを動的に追加します

私はSpring Boot Appを書いています

私の要件は次のとおりです。新しいxmlファイルを追加する場合、リソース(src/main/resources)フォルダー内にあります。これらのファイルを読み取り、各URLからいくつかのURLおよびその他の特定の設定を取得する必要があります。そして、それらのURLについては、毎日データをダウンロードする必要があります..新しいスケジューラジョブは、URLといくつかの設定で開始されます

新しいジョブは、xmlファイルに存在するcron式を使用する異なるスケジュール時間で実行されます。また、ファイルはいつでも動的に追加されます。

10
F K M N

タスクを動的にスケジュールする場合は、 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);

Springを使用すると、 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"));
    }
}

Trigger を実装することにより、独自のトリガーを提供できます。

構成クラスで@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();
}

詳細については、この記事をご覧ください: ディレクトリの変更の監視 .

30
JEY

あなたは春の注釈を介してそれを行うことができます:

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

メソッドはvoidでなければならないことに注意してください。さらに、メインクラスで、スケジューリングを有効にする必要があります。

@SpringBootApplication
@EnableScheduling
public class Application {

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

完全なリファレンスはこちらをご覧ください: https://spring.io/guides/gs/scheduling-tasks/

2
dave0688

外部動的パラメーター構成、リアルタイム監視でこのライブラリを試してください:

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
1
Neo Pham