微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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获取更多详细信息.

原文地址:https://www.jb51.cc/spring/431960.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐