【发布时间】:2012-01-26 10:31:10
【问题描述】:
Raymond Hettinger 发布了snippet,他使用标准 Python 库中的 sched 模块以特定速率(每秒 N 次)调用函数。我想知道Java中是否有等效的库。
【问题讨论】:
标签: java python function scheduling
Raymond Hettinger 发布了snippet,他使用标准 Python 库中的 sched 模块以特定速率(每秒 N 次)调用函数。我想知道Java中是否有等效的库。
【问题讨论】:
标签: java python function scheduling
看看http://quartz-scheduler.org/
Quartz 是一种功能齐全的开源作业调度服务,可以与几乎任何 Java EE 或 Java SE 应用程序集成或一起使用 - 从最小的独立应用程序到最大的电子商务系统。
【讨论】:
看看 java.util.Timer。
你可以找到使用here的例子
你也可以考虑Quartz,功能更强大,可以组合使用 带弹簧 这是example
这是我使用 java.util.Timer 你提到的代码 sn-p 的等价物
package perso.tests.timer;
import java.util.Timer;
import java.util.TimerTask;
public class TimerExample extends TimerTask{
Timer timer;
int executionsPerSecond;
public TimerExample(int executionsPerSecond){
this.executionsPerSecond = executionsPerSecond;
timer = new Timer();
long period = 1000/executionsPerSecond;
timer.schedule(this, 200, period);
}
public void functionToRepeat(){
System.out.println(executionsPerSecond);
}
public void run() {
functionToRepeat();
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new TimerExample(3);
new TimerExample(6);
new TimerExample(9);
System.out.println("Tasks scheduled.");
}
}
【讨论】:
轻量级选项是ScheduledExecutorService。
与 python sn-p 大致等效的 Java 代码是:
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public ScheduledFuture<?> newTimedCall(int callsPerSecond,
Callback<T> callback, T argument) {
int period = (1000 / callsPerSecond);
return
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
callback.on(argument);
}
}, 0, period, TimeUnit.MILLISECONDS);
}
留给读者的练习:
【讨论】:
java.util.Timer 怎么样?见this related answer。
【讨论】:
使用java.util.Timer class怎么样?
你可以找到示例代码here
【讨论】: