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

时间:2017-10-27 11:45:38

标签: spring job-scheduling spring-boot-actuator

我正在写一个Spring Boot App

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

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

3 个答案:

答案 0 :(得分:25)

如果您想动态安排任务,可以使用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"));
    }
}

您可以通过实施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();
}

请查看此文章:Watching a Directory for Changes了解更多详情。

答案 1 :(得分:1)

你可以通过弹簧注释来做到这一点:

@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/

答案 2 :(得分:0)

尝试使用此库进行外部动态参数配置,实时监控:

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