How to use Timer class to call a method, do something, reset timer, repeat?

前端 未结 5 1016
离开以前
离开以前 2020-11-28 08:33

I\'m a Java beginner and have been futzing around with various solutions to this problem and have gotten myself kind of knotted up. I\'ve tried with Threads and then discove

5条回答
  •  孤街浪徒
    2020-11-28 09:22

    Think of a scenario where I want my code to execute at a particular time in my application or at sometime later from the current time. In other words, I want to schedule my task at the definite time.

    Java Timer class (java.util.Timer) allows an application to schedule the task on a separate background thread.

    Here is the simplest example of Java Timer:

    import java.util.Timer;
    import java.util.TimerTask;
    public class JavaTimer {
        public static void main(String[] args) {
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    System.out.println("Inside Timer Task" + System.currentTimeMillis());
                }
            };
    
            System.out.println("Current time" + System.currentTimeMillis());
            timer.schedule(task, 10000,1000);
            System.out.println("Current time" + System.currentTimeMillis());
        }
    }
    

    Output:
    Current time1455469505220
    Current time1455469505221
    Inside Timer Task1455469515222
    Inside Timer Task1455469516222
    Inside Timer Task1455469517222
    Inside Timer Task1455469518222
    Inside Timer Task1455469519222
    Inside Timer Task1455469520222
    Inside Timer Task1455469521222
    Inside Timer Task1455469522222
    Inside Timer Task1455469523222
    Inside Timer Task1455469524222
    Inside Timer Task1455469525222
    Inside Timer Task1455469526222
    Inside Timer Task1455469527222
    Inside Timer Task1455469528223
    Inside Timer Task1455469529223 and it goes on
    

    ANALYSIS : The call to timer.schedule(task, 10000,1000) is going to schedule the task which is going to execute for first time (on another thread) after 10 second from this call. After that it will call again after delay of 10 seconds. It is important to mention here that if the task cannot be started after 10 seconds, next task call will not get pre-pond. So here the delay time between two consecutive task is fixed.

    Source: Java Timer Example

提交回复
热议问题