Is there a code to check if a timer is running?

I don't see anything in the documentation that provides for checking the status on a TimerTask object (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/TimerTask.html) so one option would be to extend TimerTask and create your own class. Instead of using an anonymous TimerTask, you could create something along the lines of:

public class CoresTimerTask extends TimerTask {

    private boolean hasStarted = false;

    @Overrides
    public void run() {
        this.hasStarted = true;
        //rest of run logic here...
    }

    public boolean hasRunStarted() {
        return this.hasStarted;
    }
}

and just maintain a reference to this CoresTimerTask object, which you then pass into startTimer(). You can then later check this object via hasRunStarted.


public long scheduledExecutionTime()

Returns the scheduled execution time of the most recent actual execution of this task. (If this method is invoked while task execution is in progress, the return value is the scheduled execution time of the ongoing task The return value is undefined if the task has yet to commence its first execution.

This method is typically not used in conjunction with fixed-delay execution repeating tasks, as their scheduled execution times are allowed to drift over time, and so are not terribly significant.

  1. first thing periodically running tasks need set/reset state flag
  2. second (when i look at examples) it is better to seal this type of class

but if someone insist to have such methods

   public abstract class NonInterruptableTask extends TimerTask {

        protected boolean isDone = false;

        public boolean isDone() {return isDone;}

        protected abstract void doTaskWork();

        @Override
        public void run() {
            isDone = false;
            doTaskWork();
            isDone = true;
        }

  }

usage:

  TimerTask myTask = new NonInterruptableTask() {

       @Override 
       public void doTaskWork() {

          //job here 
       }
  };

Tags:

Timer

Java