首页 > 其他 > 详细

timer和ScheduledThreadPoolExecutor定时任务和每日固定时间执行

时间:2019-10-25 16:06:53      阅读:351      评论:0      收藏:0      [点我收藏+]

//ScheduledThreadPoolExecutor每三秒执行一次

    public static void main(String[] args) {
        ScheduledThreadPoolExecutor  scheduled = new ScheduledThreadPoolExecutor(2);
        scheduled.scheduleAtFixedRate(new Runnable() {
            int i = 0;
            @Override
            public void run() {
                System.out.println("执行"+i++);
            }
        },0,3000,TimeUnit.MILLISECONDS);

}

//timer每三秒执行一次

    public static void main(String[] args) {
        Date sendDate = new Date();
        Timer dTimer = new Timer();
        dTimer.schedule(new TimerTask() {
            @Override

       int i = 0;
            public void run() {
                System.out.print("执行"+i++);
            }
        }, sendDate,3000);

}

//timer每日定时执行一次

    public static void main(String[] args) {
        long daySpan = 24 * 60 * 60 * 1000;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 15:29:00");
        try {
            Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
            if (System.currentTimeMillis() > startTime.getTime()){
                startTime = new Date(startTime.getTime() + daySpan);
            }
            Timer t = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    System.out.print("定时器执行");
                }
            };
            t.schedule(task, startTime, daySpan);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

timer和ScheduledThreadPoolExecutor定时任务和每日固定时间执行

原文:https://www.cnblogs.com/-llf/p/11738298.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!