Raymond Hettinger发布了snippet,他使用标准Python库中提供的调度模块来调用具有特定速率(每秒N次)的函数。我想知道Java中是否有相同的库。Python sched模块是否有Java等价物?
3
A
回答
4
看看java.util.Timer。
你可以找到使用的例子here
你也可以考虑石英,这是更为强大,可以在组合 与Spring 这里使用是example
这里是我相当于用你提到的代码片段的java.util.Timer
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.");
}
}
5
看看http://quartz-scheduler.org/
石英是可以与集成,或者伴随虚拟的任何Java EE和Java SE应用程序一个全功能的,开源的作业调度服务 - 从最小的立场 - 最大的电子商务系统的应用程序。
0
你可以找到示例代码here
2
一种轻质的选择是ScheduledExecutorService。
的大致相当于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);
}
练习留给读者:
- 定义回调接口
- 决定如何处理返回的未来做
- 切记关闭执行器
+0
+1可能是最好的解决方案。有趣的是,Java代码片段的时间并不比Python相当长。 – helpermethod
+0
谢谢!我狡猾地省略了一些样板文件:) –
1
java.util.Timer
怎么样?请参阅this related answer。
相关问题
- 1. Perl模块Term :: VT102是否有Python等价物?
- 2. Python模块中是否有C的main()等价物?
- 3. 在Python中是否有sessionInfo()等价物?
- 4. Filehelpers,Super CSV:是否有Python等价物?
- 5. 是否有Python的RedBeanPHP等价物?
- 6. 是否有Python的Term :: ANSIScreen等价物?
- 7. 在Python中是否有Rake等价物?
- 8. 是否有“python -i”的ruby等价物?
- 9. R的h2o.stack是否有python等价物?
- 10. 是否有.Net System.Data的Java等价物?
- 11. excel vlookup是否有Java的等价物?
- 12. 在Java中是否有TweenMax等价物
- 13. 在java中是否有array_intersect()等价物?
- 14. 是否有IConvertible/System.Convert的Java等价物?
- 15. 是否有Ruby超时模块的Groovy等价物?
- 16. 是否有Python的all()的Java等价物?
- 17. Python是否具有抛出新Exception的Java等价物(“text here”)
- 18. 是否有Python的defaultdict的Java等价物?
- 19. 是否有Python的map函数的Java等价物?
- 20. tf_utils包是否有非GPU等价物?
- 21. 是否有一个模块等价于node.js的Python的argparse?
- 22. 是否有Android的Application :: onDestroy()等价物?
- 23. 是否有.gemrc.local或等价物?
- 24. 是否有jQuery.offset的Elm等价物?
- 25. 管道是否有'liftIO`等价物?
- 26. 是否有ToolStripButton的WPF等价物?
- 27. SecCertificateAddToKeychain是否有openssl等价物?
- 28. TabBarIOS - 是否有viewDidAppear或viewWillAppear等价物?
- 29. 在Doxygen中是否有@inheritDoc等价物?
- 30. JavaScript的Function.prototype.bind是否有Ruby等价物?
Timer类和Quartz库都提供类似cron的界面,在特定时间安排作业或每N个时间单元进行一次。我需要的是一个调度程序,它调度任务以达到特定的速率,例如,每个时间单位调用N个函数(方法)。就像在我发布@Tichodroma – dkart
@ dkart的片段中一样,正如您在我的答案中所看到的,创建具有您期望的行为的应用程序非常容易...除非我错过了某件东西 –
thanx很多@Champagne我认为这是我需要的! – dkart