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
Newsletter
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

  • Delegated Transport, Forked Authorization: Where Chat and AI-Agent Integrations Actually Break
  • Guess the Speed: Building a Family Internet Speed Guessing Game
  • Replay, Scheduling, and Throttling: Engineering a Self-Service Kafka Streaming Tool at Scale
  • Supercharging AI Agents with Azure Context: A Hands-On Guide to Azure MCP

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Dec. 20, 16 · Code Snippet
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
40.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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