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

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

我正在写一个Spring Boot App

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

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

最佳答案
如果您想动态安排任务,可以在没有弹簧的情况下使用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,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,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 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

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

猜你在找的Spring相关文章