Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
ScheduledExecutorService Interface in Java
Next article icon

ScheduledExecutorService Interface in Java

Last Updated : 11 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The ScheduledExecutorService interface in Java is a sub-interface of ExecutorService interface defined in java.util.concurrent package. This interface is used to run the given tasks periodically or once after a given delay. The ScheduledExecutorService interface has declared some useful methods to schedule the given tasks. These methods are implemented by the ScheduledThreadPoolExecutor class.

Declaration

public interface ScheduledExecutorService extends ExecutorService  

The Hierarchy of ScheduledExecutorService

ScheduledExecutorService Interface in Java

Implementing class

The implementing class of ScheduledExecutorService is ScheduledThreadPoolExecutor.

Creating a ScheduledExecutorService object 

Since ScheduledExecutorService is an interface, so it can not be instantiated. But the Executors class, defined in java.util.concurrent package, provides some factory methods that return ScheduledExecutorService objects( objects of its implementing classes )

  • public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) : Creates a new scheduled thread pool with a given core pool size (corePoolSize) and returns a ScheduledExecutorService object which can be downcasted to ScheduledThreadPoolExecutor object. This object can be used to run tasks after a given delay or to execute periodically.
     
  • public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize , ThreadFactory threadFactory) : Creates a new scheduled thread pool with a given core pool size (corePoolSize) and returns a ScheduledExecutorService object which can be downcasted to ScheduledThreadPoolExecutor object. The second argument is a ThreadFactory object that is used when a new thread is created.

Example of ScheduledExecutorService interface : 

Java
// Java Program to demonstrate // SchedulerExecutorService  import java.util.concurrent.*; import java.util.*; import java.io.*;  class SchedulerExecutorServiceExample {        public static void main(String[] args)     {         System.out.println(             "A count-down-clock program that counts from 10 to 0");          // creating a ScheduledExecutorService object         ScheduledExecutorService scheduler             = Executors.newScheduledThreadPool(11);          // printing the current time         System.out.println(             "Current time : "             + Calendar.getInstance().get(Calendar.SECOND));          // Scheduling the tasks         for (int i = 10; i >= 0; i--) {             scheduler.schedule(new Task(i), 10 - i,                                TimeUnit.SECONDS);         }          // remember to shutdown the scheduler         // so that it no longer accepts           // any new tasks         scheduler.shutdown();     } }  class Task implements Runnable {     private int num;     public Task(int num) { this.num = num; }     public void run()     {         System.out.println(             "Number " + num + " Current time : "             + Calendar.getInstance().get(Calendar.SECOND));     } } 


Output:

A count-down-clock program that counts from 10 to 0  Current time : 28  Number 10 Current time : 28  Number 9 Current time : 29  Number 8 Current time : 30  Number 7 Current time : 31  Number 6 Current time : 32  Number 5 Current time : 33  Number 4 Current time : 34  Number 3 Current time : 35  Number 2 Current time : 36  Number 1 Current time : 37  Number 0 Current time : 38  

This is a Countdown Clock that counts from 10 to 0. The ScheduledExexutorService object i.e; scheduler is created using the Executors.newScheduledThreadPool(int corePoolSize) method. 

Note: All the tasks executed after (10 - i) seconds delay from the invocation of schedule() method. The value of the current time may vary in the output based on the time of execution.

Methods of ScheduledExecutorService

METHOD

DESCRIPTION

schedule(Runnable command, long delay, TimeUnit unit)Submits a one-shot task that becomes enabled after the given delay.
schedule​(Callable<V> callable, long delay, TimeUnit unit)Submits a value-returning one-shot task that becomes enabled after the given delay.
scheduleAtFixedRate​(Runnable command, long initialDelay, long period, TimeUnit unit)Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is, executions will commence after initialDelay, then initialDelay + period, then initialDelay + 2 * period, and so on.
scheduleWithFixedDelay​(Runnable command, long initialDelay, long delay, TimeUnit unit)Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

Methods declared in interface java.util.concurrent.Executor

METHOD

DESCRIPTION

execute​(Runnable command)Executes the given command at some time in the future.

Methods declared in interface java.util.concurrent.ExecutorService

METHOD

DESCRIPTION

awaitTermination​(long timeout, TimeUnit unit)Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
invokeAll​(Collection<? extends Callable<T>> tasks)Executes the given tasks, returning a list of Futures holding their status and results when all complete.
invokeAll​(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first.
invokeAny​(Collection<? extends Callable<T>> tasks)Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do.
invokeAny​(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses.
isShutdown()Returns true if this executor has been shut down.
isTerminated()Returns true if all tasks have completed following shut down.
shutdown()Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
shutdownNow()Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
submit​(Runnable task)Submits a Runnable task for execution and returns a Future representing that task.
submit​(Runnable task, T result)Submits a Runnable task for execution and returns a Future representing that task.
submit​(Callable<T> task)Submits a value-returning task for execution and returns a Future representing the pending results of the task.

Next Article
ScheduledExecutorService Interface in Java

S

samufo
Improve
Article Tags :
  • Java
  • Java-concurrent-package
Practice Tags :
  • Java

Similar Reads

    Java Modules - Service Interface Module
    Service Provider Interface, a feature of Java 6, makes it possible to find and load implementations that adhere to a specified interface. In this article, we'll introduce Java SPI's components and demonstrate how to use it in a real-world scenario. a well-known collection of programming classes and
    3 min read
    Queue Interface In Java
    The Queue Interface is a part of java.util package and extends the Collection interface. It stores and processes the data in order means elements are inserted at the end and removed from the front. Key Features:Most implementations, like PriorityQueue, do not allow null elements.Implementation Class
    12 min read
    TransferQueue Interface in Java
    The TransferQueue interface is a member of the Java Collections Framework. It was introduced in JDK 1.7, it belongs to java.util.concurrent package. The TransferQueue is a BlockingQueue in which a sending thread(producer) may wait for the receiving thread(consumers) to receive elements. TransferQueu
    8 min read
    ScheduledThreadPoolExecutor Class in Java
    ScheduledThreadPoolExecutor class in Java is a subclass of ThreadPoolExecutor class defined in java.util.concurrent package. As it is clear from its name that this class is useful when we want to schedule tasks to run repeatedly or to run after a given delay for some future time. It creates a fixed-
    6 min read
    Service Client Module in Java
    A Client Module in Java is a set of classes and methods that are used to connect to, interact with, and consume services from a server. It is the front-end component of a client/server architecture. It is typically responsible for initiating communication with the server, sending and receiving data,
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences