Java Scheduler ScheduledExecutorService ScheduledThreadPoolExecutor Example

Filed Under: Java

Welcome to the Java Scheduler Example. Today we will look into ScheduledExecutorService and it’s implementation class ScheduledThreadPoolExecutor example.

Java Scheduler ScheduledExecutorService

java scheduler, java scheduler example, ScheduledExecutorService, ScheduledThreadPoolExecutor
Sometimes we need to execute a task periodically or after specific delay. Java provides Timer Class through which we can achieve this but sometimes we need to run similar tasks in parallel. So creating multiple Timer objects will be an overhead to the system and it’s better to have a thread pool of scheduled tasks.

Java provides scheduled thread pool implementation through ScheduledThreadPoolExecutor class that implements ScheduledExecutorService interface. ScheduledExecutorService defines the contract methods to schedule a task with different options.

Sometime back I wrote a post about Java ThreadPoolExecutor where I was using Executors class to create the thread pool. Executors class also provide factory methods to create ScheduledThreadPoolExecutor where we can specify the number of threads in the pool.

Java Scheduler Example

Let’s say we have a simple Runnable class like below.

WorkerThread.java


package com.journaldev.threads;

import java.util.Date;

public class WorkerThread implements Runnable{

private String command;
    
    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" Start. Time = "+new Date());
        processCommand();
        System.out.println(Thread.currentThread().getName()+" End. Time = "+new Date());
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString(){
        return this.command;
    }
}

It’s a simple Runnable class that takes around 5 seconds to execute its task.

Let’s see a simple example where we will schedule the worker thread to execute after 10 seconds delay. We will use Executors class newScheduledThreadPool(int corePoolSize) method that returns instance of ScheduledThreadPoolExecutor. Here is the code snippet from Executors class.


public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

Below is our java scheduler example program using ScheduledExecutorService and ScheduledThreadPoolExecutor implementation.


package com.journaldev.threads;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class ScheduledThreadPool {

	public static void main(String[] args) throws InterruptedException {
		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
		
		
		//schedule to run after sometime
		System.out.println("Current Time = "+new Date());
		for(int i=0; i<3; i++){
			Thread.sleep(1000);
			WorkerThread worker = new WorkerThread("do heavy processing");
			scheduledThreadPool.schedule(worker, 10, TimeUnit.SECONDS);
		}
		
		//add some delay to let some threads spawn by scheduler
		Thread.sleep(30000);
		
		scheduledThreadPool.shutdown();
		while(!scheduledThreadPool.isTerminated()){
			//wait for all tasks to finish
		}
		System.out.println("Finished all threads");
	}

}

When we run above java scheduler example program, we get following output that confirms that tasks are running with 10 seconds delay.


Current Time = Tue Oct 29 15:10:03 IST 2013
pool-1-thread-1 Start. Time = Tue Oct 29 15:10:14 IST 2013
pool-1-thread-2 Start. Time = Tue Oct 29 15:10:15 IST 2013
pool-1-thread-3 Start. Time = Tue Oct 29 15:10:16 IST 2013
pool-1-thread-1 End. Time = Tue Oct 29 15:10:19 IST 2013
pool-1-thread-2 End. Time = Tue Oct 29 15:10:20 IST 2013
pool-1-thread-3 End. Time = Tue Oct 29 15:10:21 IST 2013
Finished all threads

Note that all the schedule() methods return instance of ScheduledFuture that we can use to get the thread state information and delay time for the thread.

ScheduledFuture extends Future interface, read more about them at Java Callable Future Example.

There are two more methods in ScheduledExecutorService that provide option to schedule a task to run periodically.

ScheduledExecutorService scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit)

We can use ScheduledExecutorService scheduleAtFixedRate method to schedule a task to run after initial delay and then with the given period.

The time period is from the start of the first thread in the pool, so if you are specifying period as 1 second and your thread runs for 5 second, then the next thread will start executing as soon as the first worker thread finishes it’s execution.

For example, if we have code like this:


for (int i = 0; i < 3; i++) {
	Thread.sleep(1000);
	WorkerThread worker = new WorkerThread("do heavy processing");
	// schedule task to execute at fixed rate
	scheduledThreadPool.scheduleAtFixedRate(worker, 0, 10,
	TimeUnit.SECONDS);
}

Then we will get output like below.


Current Time = Tue Oct 29 16:10:00 IST 2013
pool-1-thread-1 Start. Time = Tue Oct 29 16:10:01 IST 2013
pool-1-thread-2 Start. Time = Tue Oct 29 16:10:02 IST 2013
pool-1-thread-3 Start. Time = Tue Oct 29 16:10:03 IST 2013
pool-1-thread-1 End. Time = Tue Oct 29 16:10:06 IST 2013
pool-1-thread-2 End. Time = Tue Oct 29 16:10:07 IST 2013
pool-1-thread-3 End. Time = Tue Oct 29 16:10:08 IST 2013
pool-1-thread-1 Start. Time = Tue Oct 29 16:10:11 IST 2013
pool-1-thread-4 Start. Time = Tue Oct 29 16:10:12 IST 2013

ScheduledExecutorService scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit)

ScheduledExecutorService scheduleWithFixedDelay method can be used to start the periodic execution with initial delay and then execute with given delay. The delay time is from the time thread finishes it’s execution. So if we have code like below:


for (int i = 0; i < 3; i++) {
	Thread.sleep(1000);
	WorkerThread worker = new WorkerThread("do heavy processing");
	scheduledThreadPool.scheduleWithFixedDelay(worker, 0, 1,
	TimeUnit.SECONDS);
}

Then we will get output like below.


Current Time = Tue Oct 29 16:14:13 IST 2013
pool-1-thread-1 Start. Time = Tue Oct 29 16:14:14 IST 2013
pool-1-thread-2 Start. Time = Tue Oct 29 16:14:15 IST 2013
pool-1-thread-3 Start. Time = Tue Oct 29 16:14:16 IST 2013
pool-1-thread-1 End. Time = Tue Oct 29 16:14:19 IST 2013
pool-1-thread-2 End. Time = Tue Oct 29 16:14:20 IST 2013
pool-1-thread-1 Start. Time = Tue Oct 29 16:14:20 IST 2013
pool-1-thread-3 End. Time = Tue Oct 29 16:14:21 IST 2013
pool-1-thread-4 Start. Time = Tue Oct 29 16:14:21 IST 2013

That’s all for java scheduler example. We learned about ScheduledExecutorService and ScheduledThreadPoolExecutorthread too. You should check other articles about Multithreading in Java.

References:

Comments

  1. Dinakaran L says:

    My desktop application hangs after 2hours, is there any bug in the following code.
    Pl.guide me

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    final Runnable beeper = new Runnable() {
    public void run() {
    //new kotprint();
    //new DinaUtil().updatetablestatus();
    System.out.println(“beep” + util.gettimewithss());
    }
    };
    executor.scheduleAtFixedRate(beeper, 10, 10, TimeUnit.SECONDS);

  2. Harshit Garg says:

    Can schedule() method can trigger a task a little early from the scheduled time.
    In my problem. a task should be triggered at 11:00 am in the morning, but it is being triggered at 10:59:48 am. In fact, the early triggering time varies between 1 sec to 12 sec.

    1. Rishad Ali says:

      I am have the same issue.
      My tasks are supposed to start at midnight. First time it was OK but the second time it started the task 2 seconds early, 23:59:58.

  3. Rams says:

    How to schedule cron jobs using cron expressions in Java? I don’t want to use quartz or other third party libraries.

  4. priyanka thool says:

    How should i kill the threads after finishing its task? I am working with quartz schedular

  5. Lava says:

    Very nice article.

    Is there any way to verify whether the invoked thread is finished or not? If the invoked thread is taking more than the expected time.. I want to kill the thread and continue.

  6. Fabio says:

    Congratulations on your article. I found it very useful. I just have a question: how can I schedule multiple different tasks in different hours of day such as:

    task 1: 7 am : “have breakfast”;
    task 2: 8 am : “go to work”;
    task 3: 1 pm: “have lunch”;
    task 4: 6 pm: “go home”
    task 5: 7 pm: “have dinner”
    task 6: 9 om: “go to sleep”

    What is the best solution to come up with an app that prints out these messages at these particular time of the day?

    Thank you in advance,

    Kind regards,

    Fábio.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages