我正在写一个Spring Boot App
我的要求是 – 在资源(src / main / resources)文件夹中,如果我添加新的xml文件..我应该阅读这些文件,并从每个文件中获取一些网址和其他特定设置.对于那些我需要每天下载数据的网址.所以新的调度程序作业将从url和一些设置开始
最佳答案
如果您想动态安排任务,可以在没有弹簧的情况下使用ExecutorService特别是ScheduledThreadPoolExecutor
原文链接:https://www.f2er.com/spring/431960.htmlRunnable 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> event : key.pollEvents()) {
WatchEvent
请查看本文:Watching a Directory for Changes以获取更多详细信息.