Skip to content
import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时任务demo
 */
public class TestTimerTask {
    static class NotifyTask extends TimerTask {
        int retryTimes;
        int curTimes = 0;
        Timer t;

        public NotifyTask(Timer t, int retryTimes) {
            this.t = t;
            this.retryTimes = retryTimes;
        }

        @Override
        public void run() {
            System.out.println("第" + curTimes + "次执行");
            if (++curTimes > retryTimes - 1) {
                System.out.println("达到次数上限,结束任务!");
                t.cancel();
                t.purge();
            }
        }
    }


    public static void main(String[] args) {
        Timer t = new Timer();

        // 最多重试5次
        TimerTask task = new NotifyTask(t, 5);

        // 延迟5秒,每隔2秒执行一次
        t.schedule(task, 5000, 2000);
    }
}

文章来源于自己总结和网络转载,内容如有任何问题,请大佬斧正!联系我