本文介绍了Javafx中“ScheduledService”的简单示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名学生,一个月以来学习JavaFX。
我正在开发一个应用程序,我希望服务在执行任务后重复启动。为此我已经知道'类。 只是具有计划功能的服务。

Considering you have a sound knowledge of Service class. ScheduledService is just a Service with a Scheduling functionality.

来自文档

所以我们可以这样说,

Service -> Execute One Task
ScheduledService -> Execute Same Task at regular intervals

计划服务的一个非常简单的例子是TimerService,它计算数字已调用服务任务的次数。它计划每1秒调用一次

A very simple example of Scheduled Service is the TimerService, which counts the number of times the Service Task has been called. It is scheduled to call it every 1 second

import java.util.concurrent.atomic.AtomicInteger;

import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.util.Duration;

public class TimerServiceApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        TimerService service = new TimerService();
        AtomicInteger count = new AtomicInteger(0);
        service.setCount(count.get());
        service.setPeriod(Duration.seconds(1));
        service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {

            @Override
            public void handle(WorkerStateEvent t) {
                System.out.println("Called : " + t.getSource().getValue()
                        + " time(s)");
                count.set((int) t.getSource().getValue());
            }
        });
        service.start();
    }

    public static void main(String[] args) {
        launch();
    }

    private static class TimerService extends ScheduledService<Integer> {
        private IntegerProperty count = new SimpleIntegerProperty();

        public final void setCount(Integer value) {
            count.set(value);
        }

        public final Integer getCount() {
            return count.get();
        }

        public final IntegerProperty countProperty() {
            return count;
        }

        protected Task<Integer> createTask() {
            return new Task<Integer>() {
                protected Integer call() {
                    //Adds 1 to the count
                    count.set(getCount() + 1);
                    return getCount();
                }
            };
        }
    }
}

这篇关于Javafx中“ScheduledService”的简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 12:28