Java定时器Timer的使用

匿名 (未验证) 提交于 2019-12-02 21:53:52

最近在实现比赛倒计时投票的功能,先后考虑使用session,CookieWebStorage 来实现,但最终采用Java定时器Timer实现了此功能。

以下是Timer的使用方法

public class TestTimer {
 public static void main(String[] args) {
        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("TimerTask is called!");
                //timer.cancel();//终止执行
            }
        };
        /*
         * schedule 和 scheduleAtFixedRate 区别:
         *  可将schedule理解为scheduleAtFixedDelay,
         *  两者主要区别在于delay和rate
         *  1、schedule,如果第一次执行被延时(delay),
         *      随后的任务执行时间将以上一次任务实际执行完成的时间为准
         *  2、scheduleAtFixedRate,如果第一次执行被延时(delay),
         *      随后的任务执行时间将以上一次任务开始执行的时间为准(需考虑同步)
         *
         *  参数:1、任务体    2、延时时间(可以指定执行日期)3、任务执行间隔时间
         */
        // timer.schedule(task, 0, 1000 * 3);
        timer.scheduleAtFixedRate(task, 0, 1000 * 3);
    }
}


参考:https://blog.csdn.net/Zhang_Zippor/article/details/53024146

转载请标明出处:Java定时器Timer的使用
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!