有与pythonsched模块等价的Java吗?

2024-09-27 00:18:12 发布

您现在位置:Python中文网/ 问答频道 /正文

raymondhettinger发布了一个snippet,其中他使用标准Python库中可用的sched模块,以便以特定速率(每秒N次)调用函数。我想知道Java中是否有一个等价的库。在


Tags: 模块标准速率javasnippet调用函数等价sched
3条回答

看看http://quartz-scheduler.org/

Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application - from the smallest stand-alone application to the largest e-commerce system.

轻量级选项是ScheduledExecutorService。在

与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);
}

留给读者的练习:

  • 定义回调接口
  • 决定如何处理回归的未来
  • 记得把遗嘱执行人关了

看看java.util.Timer. 在

您可以找到使用here的示例

你也可以考虑石英,这是更强大的,可以结合使用 有了春天 这是一个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.");
      }
}

相关问题 更多 >

    热门问题