Spring启动动态添加新的计划作业

前端之家收集整理的这篇文章主要介绍了Spring启动动态添加新的计划作业前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在写一个Spring Boot App

我的要求是 – 在资源(src / main / resources)文件夹中,如果我添加新的xml文件..我应该阅读这些文件,并从每个文件获取一些网址和其他特定设置.对于那些我需要每天下载数据的网址.所以新的调度程序作业将从url和一些设置开始

新作业将在不同的计划时间运行,这将使用xml文件中存在的cron表达式
此外,文件将在任何时间动态添加
如何实现它.

最佳答案
如果您想动态安排任务,可以在没有弹簧的情况下使用ExecutorService特别是ScheduledThreadPoolExecutor

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

春天你可以依靠Task and Scheduling API

  1. public class MyBean {
  2. private final TaskScheduler executor;
  3. @Autowired
  4. public MyBean(TaskScheduler taskExecutor) {
  5. this.executor = taskExecutor;
  6. }
  7. public void scheduling(final Runnable task) {
  8. // Schedule a task to run once at the given date (here in 1minute)
  9. executor.schedule(task,Date.from(LocalDateTime.now().plusMinutes(1)
  10. .atZone(ZoneId.systemDefault()).toInstant()));
  11. // Schedule a task that will run as soon as possible and every 1000ms
  12. executor.scheduleAtFixedRate(task,1000);
  13. // Schedule a task that will first run at the given date and every 1000ms
  14. executor.scheduleAtFixedRate(task,Date.from(LocalDateTime.now().plusMinutes(1)
  15. .atZone(ZoneId.systemDefault()).toInstant()),1000);
  16. // Schedule a task that will run as soon as possible and every 1000ms after the prevIoUs completion
  17. executor.scheduleWithFixedDelay(task,1000);
  18. // Schedule a task with the given cron expression
  19. executor.schedule(task,new CronTrigger("*/5 * * * * MON-FRI"));
  20. }
  21. }

您可以通过实施Trigger来提供自己的触发器

不要忘记在配置类上使用@EnableScheduling启用调度.

关于收听目录内容,您可以使用WatchService.类似于:

  1. final Path myDir = Paths.get("my/directory/i/want/to/monitor");
  2. final WatchService watchService = FileSystems.getDefault().newWatchService();
  3. // listen to create event in the directory
  4. myDir.register(watchService,StandardWatchEventKinds.ENTRY_CREATE);
  5. // Infinite loop don't forget to run this in a Thread
  6. for(;;) {
  7. final WatchKey key = watchService.take();
  8. for (WatchEvent

请查看本文:Watching a Directory for Changes获取更多详细信息.

猜你在找的Spring相关文章