timer和ScheduledThreadPoolExecutor定時任務和每日固定時間執行


//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();
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM