Java timer task schedule

From reading in Stack Overflow, I saw that many of you do not recommend using Timer Task. Hmm ... but I already implemented this:

I have this code:

detectionHandlerTimer.schedule(myTimerTask, 60 * 1000, 60 * 1000);

The fact is that myTimerTask has been running for a while.

I would like:

  • wait 60 seconds.
  • complete the task for some time (for example, 40-100 seconds).
  • completed task.
  • wait 60 seconds.
  • complete the task for some time (for example, 40-100 seconds).

But the above code behaves like

  • wait 60 seconds.
  • complete the task for some time (for example, 40-100 seconds).
  • task completed
  • complete the task for some time (for example, 40-100 seconds).

Since the task execution time is more than 60, the timer starts the task immediately after completion of the task. But I would like him to wait again.

+5
source share
1 answer

. , ( ) .

import java.util.Timer;
import java.util.TimerTask;

public class TaskManager {

    private Timer timer = new Timer();

    public static void main(String[] args) {
        TaskManager manager = new TaskManager();
        manager.startTask();
    }

    public void startTask() {
        timer.schedule(new PeriodicTask(), 0);
    }

    private class PeriodicTask extends TimerTask {
        @Override
        public void run() {
            System.out.println(System.currentTimeMillis() + " Running");

            /* replace with the actual task */
            try {
                Thread.sleep(15 * 1000);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            /* end task processing */

            System.out.println(System.currentTimeMillis() + " Scheduling 10 seconds from now");
            timer.schedule(new PeriodicTask(), 10 * 1000);
        }
    }
}

:

$ javac TaskManager.java && java TaskManager
1288282514688 Running
1288282529711 Scheduling 10 seconds from now
1288282539712 Running
1288282554713 Scheduling 10 seconds from now
1288282564714 Running

, ( ):

$ javac TaskManager.java && java TaskManager
14                                    Running
29 (+15 seconds execution)            Scheduling 10 seconds from now
39 (+10 seconds delay until next run) Running
54 (+15 seconds execution)            Scheduling 10 seconds from now
64 (+10 seconds delay until next run) Running

10 60 s.

+10

All Articles