【问题标题】:Executing javascript function in ScheduledExecutorService?在 ScheduledExecutorService 中执行 javascript 函数?
【发布时间】:2017-03-09 16:04:46
【问题描述】:

我使用每 1 秒运行一次的 ScheduledExecutorService 建立了一个循环。我有一个 WebView (JavaFX),我想从中调用一个函数。

如果我把它放在一个按钮上,我可以很好地调用函数:

button.setOnAction(event -> {
    webEngine.executeScript("someFunction();");
});

然后点击它,它执行得很好,但是当我这样做时:

execService.scheduleAtFixedRate(()->{
    loop();
    webEngine.executeScript("someFunction();");
}, 3000L, 1000L, TimeUnit.MILLISECONDS);

程序在webEngine.executeScript("someFunction();"); 处停止(如果我将该行放在我的loop() 方法中,也是如此)

我怎样才能在我的程序的其余部分旁边每秒执行someFunction()?为什么会暂停?

【问题讨论】:

  • 您所说的“只是停止”是什么意思?冻结/挂起?崩溃?如果是这样,堆栈跟踪说明了什么?
  • @Mena 我仍然可以单击内容并执行操作,控制台中没有任何内容,一切正常,除了应该在 scheduleexecutorservice 中执行的任何内容都没有,例如。如果我在webEngine.executeScript("someFunction();") 后面加上System.out.println("bleh"),它就达不到它

标签: javascript java javafx webview scheduledexecutorservice


【解决方案1】:

请试试这个:

timer = new Timer();
        timer.scheduleAtFixedRate(new WebViewProcess(), 3000, 1000);

private class WebViewProcess extends TimerTask {

        @Override
        public void run() {
            Platform.runLater(() -> {
                    webEngine.executeScript("someFunction();");
            });
        }
    }

【讨论】:

  • 很高兴为您提供帮助
  • 请注意,Timer 已弃用,ScheduledExecutorService 是推荐的替代品。可能这里的解决方案是在 Platform.runLater 异步调用上。
  • @Mena 是的,那是我使用并开始工作的部分 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多