Timer定时执行

//定时器
    public void timeTask(String hh,int n) {//hh="8:30:00",n=12
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                //Upload();
                System.out.println("成功");
            }
        };
        // 规定的每天时间08:00:00运行
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd '"+hh+"'");
        // 首次运行时间
        Date startTime = null;
        try {
            startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 如果今天的已经过了 首次运行时间就改为明天
        if (System.currentTimeMillis() > startTime.getTime()) {
            Calendar startDT = Calendar.getInstance();
            startDT.setTime(startTime);
            startDT.add(Calendar.DATE, 1);
            startTime=startDT.getTime();
        }
        // timer.schedule(task, 60*1000);
        // 60*1000 一分钟
        timer.scheduleAtFixedRate(task, startTime, n * 60 * 60 * 1000);
        System.out.println("执行完了");
    }

 

posted @ 2018-03-11 20:54  非非是  阅读(152)  评论(0编辑  收藏  举报