java program run regularly

        But also you need a program run on a recurring, but he needs to run, rather than requiring programmers to run at regular intervals, this is the need to use TimerTask class, the specific circumstances of the code below:

package dingshi;

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

public class dingshi {

	public static void main(String[] args) {
		Timer timer = new Timer();
		MyTask task = new MyTask();
        //表示在1秒之后开始执行,并且每2秒执行一次
        timer.schedule(task, 1000, 2000);
	}
}
	
class MyTask extends TimerTask{

    //在run方法中的语句就是定时任务执行时运行的语句。
    public void run() {
    		System.out.println("Hello!! 现在是:" + new Date());
    }
}

Pure the output operates as follows:

Hello!! 现在是:Wed Mar 13 21:01:57 CST 2019
Hello!! 现在是:Wed Mar 13 21:01:59 CST 2019
Hello!! 现在是:Wed Mar 13 21:02:01 CST 2019
Hello!! 现在是:Wed Mar 13 21:02:03 CST 2019
Hello!! 现在是:Wed Mar 13 21:02:05 CST 2019
Hello!! 现在是:Wed Mar 13 21:02:07 CST 2019

Indeed it can be seen running about two seconds per run () method.

If the run () event runs over the set of 2 seconds, the run () will then run after run to completion, two seconds if no longer work, as follows, () procedure wait 5 seconds added to the run method :

package dingshi;

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

public class dingshi2 {

	public static void main(String[] args) {
		Timer timer = new Timer();
		MyTask task = new MyTask();
        //表示在1秒之后开始执行,并且每2秒执行一次
        timer.schedule(task, 1000, 2000);
	}
}
	
class MyTask extends TimerTask{

    //在run方法中的语句就是定时任务执行时运行的语句。
    public void run() {
    		System.out.println("Hello!! 现在是:" + new Date());
    		try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }
}

Then the result would this be:

Hello!! 现在是:Wed Mar 13 21:06:07 CST 2019
Hello!! 现在是:Wed Mar 13 21:06:12 CST 2019
Hello!! 现在是:Wed Mar 13 21:06:17 CST 2019
Hello!! 现在是:Wed Mar 13 21:06:22 CST 2019
Hello!! 现在是:Wed Mar 13 21:06:27 CST 2019

 

 

Guess you like

Origin blog.csdn.net/a857553315/article/details/88541321