Shashank Shekher Shashank Shekher - 1 year ago 63
Java Question

Continuous Monitoring of a function in Java on a single thread

I have a method in a particular class for which I need subsequent executions to take place at approximately regular intervals separated by the specified period. I need to do this using a


Also, even when this method gets called multiple times from anywhere, I want the same thread to be executed without starting a new thread.

How can i achieve this?

Answer Source
  1. Create an implementation class of Runnable(Make it singleton)

    public class MainTask implements Runnable {
        private static MainTask mainTask;
        private MainTask(){ }
        public static MainTask getInstance(){
                mainTask = new MainTask();
            return mainTask;
        public void run() {
            // task to run goes here
            System.out.println("Hello !! " + Thread.currentThread().getName());
  2. Make use of scheduleAtFixedRate's method of ScheduledExecutorService method in order to execute the task at regular intervals separated by specified period.

    Its method definition is

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

    where period = period between successive executions. Note that this value could be min/hrs/days etc depending on TimeUnit configured.

  3. As this feature is something you would want it to be used by other classes I suggest you can encapsulate the thread creation and task creation in another class and allow it to be used by Class.methodName for.e.g MyScheduler.execute();

     public class MyScheduler {
        private static ScheduledExecutorService service;
        private static MainTask mainTask;
        static {
            service = Executors.newSingleThreadScheduledExecutor();
            mainTask = MainTask.getInstance();
        public static void execute() {
            service.scheduleAtFixedRate(mainTask, 0, 4, TimeUnit.SECONDS);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download