DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques
  • Keep Your Application Secrets Secret
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)

Trending

  • The Invisible OOMKill: Why Your Java Pod Keeps Restarting in Kubernetes
  • Pragmatica Aether: Let Java Be Java
  • Your AI Agent Tests Are Passing, But Your Agent Is Still Broken
  • Every Cache Miss Is a Tiny Tax on Your Performance
  1. DZone
  2. Coding
  3. Java
  4. A Look at ScheduledService [Code Snippets]

A Look at ScheduledService [Code Snippets]

ScheduledService lets you execute the same task a regular intervals and can even restart itself in the event of a failure, making it a good tool to have in the box.

By 
Arun Pandey user avatar
Arun Pandey
DZone Core CORE ·
Dec. 20, 16 · Code Snippet
Likes (8)
Comment
Save
Tweet
Share
40.1K Views

Join the DZone community and get the full member experience.

Join For Free

ScheduledService is a very nice feature of Java 8 present under the javafx.concurrent package.

In general, a service is a program that encapsulates all the essential information to execute tasks. The same way, the ScheduledService API works for us, but a difference is that it executes the same task at regular intervals, and it has the capability of restarting itself after a successful execution. There could be possible conditions when it could restart itself in the event of a failure as well.

The only way to work with JavaFX is to subclass Application in stand-alone applications because it needs to prepare the environment and toolkit — otherwise, it will throw the exception 'Exception in thread "main" java.lang.IllegalStateException: Toolkit not initialized.'

Let us look at an example:

Counter.java

package scheduledservice.test;

/**
 * @author arun.pandey
 */
public class Counter{
  private int count = 0;

  public int getCount() {
    return count;
  }
  public void setCount(int count) {
    this.count = count;
  }
}


CounterService.java

package scheduledservice.test;

import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;

/**
 * @author arun.pandey
 */
public class CounterService extends ScheduledService<Object> {
  private Counter obj;

  public final void setObject(Counter obj) {
    this.obj = obj;
  }

  @Override
  protected Task<Object> createTask() {
    return new Task<Object>() {
      protected Integer call() {
        obj.setCount(obj.getCount()+1);
        return obj.getCount();
      }
    };
  }
}


Now let us look at the client code.

CounterServiceApplication.java

package scheduledservice.test;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javafx.application.Application;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * @author arun.pandey
 */
public class CounterServiceApplication extends Application {
  public static final Log LOG = LogFactory.getLog(CounterServiceApplication.class); 

  @Override
  public void start(Stage stage) throws Exception {
    CounterService counterServc = new CounterService();
    Counter oc = new Counter();
    counterServc.setObject(oc);
    counterServc.setPeriod(Duration.seconds(1));

    counterServc.setOnSucceeded(new EventHandler<WorkerStateEvent>() {

      @Override
      public void handle(WorkerStateEvent event) {
        LOG.info("Getting called : " + event.getSource().getValue() + " times");
        oc.setCount((int) event.getSource().getValue());
      }
    });
    counterServc.start();
  }

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


The output can be seen as below:

Image title


I hope this gives you an understanding of the ScheduledService API. Happy learning!

Snippet (programming) application Task (computing) API JavaFX Execution (computing) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques
  • Keep Your Application Secrets Secret
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook