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

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • Chaos Engineering for Microservices
  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Optimize Deployment Pipelines for Speed, Security and Seamless Automation
  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
39.8K 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.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: