1

I know there are many frameworks for Scheduler as well as JDK's own Scheduler. I can't use any third party framework/API. The existing scheduler uses only Java API. It is as follows:-

    public class Timer implements Runnable {

    private Thread runner;
    private int pause;
    private Task task;
    private boolean running;

    public Timer(int pause, Task task) {
        this.pause = pause;
        this.task = task;
        runner = new Thread(this, "Timer");
    }

    public void run() {
        try {
          while (running) {
            task.run(); // long running task
            synchronized (runner) {
                runner.wait(pause);
            }
        }
    } catch (InterruptedException ie) {
        /* The user probably stopped the */
    }
 }

Interface and class:-

public interface Task {

    void run();
 }

public class TaskManager implements Task {

private static boolean firstRun = true;
private static Timer timer;
private static String lastRun;


public static void start(int interval) {

    // stop any previous
    if (timer != null) {
        timer.stopTimer();
        timer = null;
    }

    // Start a new one
    TaskManager taskManager = new TaskManager ();
    timer = new Timer(interval * 1000, taskManager );
    timer.startTimer();
}    


  public void run() {
  // long running code
  }

public void setDelay(int p) {
    pause = p;
}

public void startTimer() {
    running = true;
    runner.start();
}

public void stopTimer() {
    running = false;
    runner.interrupt();
  }
}

From a servelet I call as:

private void startTaskManager() {
    TaskManager.start(30);
}

My requirements that it will perform task in a thread in the run() method. There are many tasks that will be picked one after another from the database.

The above implementation has some issues. On the above implementation, it has own interface Task and implemented own Timer.

I think there is another better way to achieve this scheduler. Please suggest me.

0xadecimal
  • 696
  • 5
  • 18
masiboo
  • 4,537
  • 9
  • 75
  • 136

0 Answers0