【发布时间】:2015-09-02 12:56:38
【问题描述】:
我已弃用方法Scheduler.addPeriodicJob。我想重构我的代码并将其替换为 Scheduler.scheduleScheduleOptions接口怎么做以及如何通过它传递值?
【问题讨论】:
标签: java refactoring aem sling
我已弃用方法Scheduler.addPeriodicJob。我想重构我的代码并将其替换为 Scheduler.scheduleScheduleOptions接口怎么做以及如何通过它传递值?
【问题讨论】:
标签: java refactoring aem sling
看看this page。 看起来你需要像这样替换每个调用:
Scheduler s;
s.addPeriodicJob(name, job, config, period, canRunConcurrently);
类似的东西
Scheduler s;
ScheduleOptions so = Scheduler.NOW(times, period); // times == -1 for endless
so.canRunConcurrently(canRunConcurrently);
so.config(config);
so.name(name);
s.schedule(job, so);
【讨论】:
如果您有很多要修复的参考,则应使用此解决方案。
您可以在代码库中创建一个类 org.apache.sling.commons.scheduler.Scheduler 并声明旧方法和新方法:
public class Scheduler {
@Deprecated
public void addPeriodicJob(String name,
Object job,
Map<String,Serializable> config,
long period,
boolean canRunConcurrently)
throws Exception {
ScheduleOptions options = NOW(-1, period)
.name(name)
.config(config)
.canRunConcurrently(canRunConcurrently);
schedule(job, options);
}
public boolean schedule(Object job, ScheduleOptions options) {
// dummy placeholder to let the code compile
return false;
}
}
(您可能需要实现Scheduler 接口的所有方法,以使您的代码编译并让重构按预期工作)
然后,将 addPeriodicJob() 方法与 IDE 的重构工具内联。
最后,删除您在代码库中创建的 Scheduler 类。
您现在应该已经迁移了所有代码!
您终于有了必须的清理步骤(我怎么强调都不为过):
那么您可能应该删除所有不必要的代码或默认值。
例如我的测试样本:
public static void main(String[] args) {
Scheduler scheduler = new Scheduler();
scheduler.addPeriodicJob("name", new Object(), Collections.EMPTY_MAP, 10, false);
}
结局是这样的:
public static void main(String[] args) {
Scheduler scheduler = new Scheduler();
ScheduleOptions options = scheduler.NOW(-1, (long) 10).name("name").config((Map<String, Serializable>) Collections.EMPTY_MAP).canRunConcurrently(false);
scheduler.schedule(new Object(), options);
}
你可以做一些重新格式化和清理到这里结束:
public static void main(String[] args) {
Scheduler scheduler = new Scheduler();
ScheduleOptions options = scheduler
.NOW(-1, 10)
.name("name")
.config(Collections.EMPTY_MAP)
.canRunConcurrently(false);
scheduler.schedule(new Object(), options);
}
如果你删除了设置默认值或无意义值的代码,你甚至可能会得到(我想,因为我对 sling 一无所知):
public static void main(String[] args) {
Scheduler scheduler = new Scheduler();
scheduler.schedule(new Object(), scheduler.NOW(-1, 10));
}
【讨论】: