是否存在Python sched模块的Java等价物?
Raymond Hettinger发布了一篇文章,其中他使用标准Python库中可用的sched模块以特定速率(每秒N次)调用函数。我想知道Java中是否有等效的库。看看 Quartz是一种功能齐全的开源作业调度服务,可以与任何Java EE或Java SE应用程序(从最小的独立应用程序到最大的电子商务系统)集成,或与之一起使用 用电脑怎么样是否存在Python sched模块的Java等价物?,java,python,function,scheduling,Java,Python,Function,Scheduling,Raymond Hettinger发布了一篇文章,其中他使用标准Python库中可用的sched模块以特定速率(每秒N次)调用函数。我想知道Java中是否有等效的库。看看 Quartz是一种功能齐全的开源作业调度服务,可以与任何Java EE或Java SE应用程序(从最小的独立应用程序到最大的电子商务系统)集成,或与之一起使用 用电脑怎么样 您可以找到示例代码一个轻量级选项是 与python代码片段大致相当的Java代码是: private final ScheduledExecutorSer
您可以找到示例代码一个轻量级选项是 与python代码片段大致相当的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);
}
private final ScheduledExecutorService调度器=
Executors.newScheduledThreadPool(1);
公共计划未来新时间调用(int calls秒,
回调(T参数){
整数周期=(1000次/呼叫秒);
返回
scheduleAtFixedRate(新的Runnable(){
公开募捐{
关于(参数);
}
},0,周期,时间单位为毫秒);
}
留给读者的练习:
- 定义回调接口
- 决定如何处理返回的未来
- 记住关闭遗嘱执行人
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.");
}
}
java.util.Timer怎么样?请参阅。Timer类和Quartz库都提供了类似cron的接口,可以在特定时间安排作业,也可以每N个时间单位安排一次作业。我需要的是一个调度程序,它可以调度任务以达到特定的速率,例如,每个时间单位有N个函数(方法)调用。就像我发布的片段一样@Tichodroma@dkart,正如您在我的回答中所看到的,创建一个具有您期望的行为的应用程序非常容易……除非我错过了很多东西@C。我想这就是我所需要的!欢迎@dkart!请不要忘记在回答问题的答案上加上标记。+1可能是最好的解决方案。有趣的是,Java代码片段并不比Python等效代码长那么多。谢谢!我确实巧妙地漏掉了一些样板:)