java timer task schedule

后端 未结 1 762
灰色年华
灰色年华 2020-12-01 22:34

From reading on Stack Overflow I\'ve seen that many of you don\'t recommend using Timer Task. Hmmm... but I already implemented this:

I have this code:



        
相关标签:
1条回答
  • 2020-12-01 23:10

    This works. The key is to have the task itself (after it completes) schedule the next occurrence of the task.

    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);
            }
        }
    }
    

    Which prints:

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

    Here's what it looks like if you extract the second components of the timestamps (for clarity):

    $ 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
    

    Just replace the 10s with 60s.

    0 讨论(0)
提交回复
热议问题