Java里的定时任务

方法调用

try {
    // 每天12点执行定时任务
    timing("12:00:00");
} catch (ParseException e) {
    e.printStackTrace();
}

方法体



/**
* @param time 每天几点执行定时任务   24小时制时间 例: 08:00:00  20:00:00
* @throws ParseException
*/
private void timing(String time) throws ParseException {
    int hour = Integer.parseInt(time.substring(0, 2));
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 获取当前小时
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    int currentHour = calendar.get(Calendar.HOUR_OF_DAY);

    long delayTime;
    long currentTime = System.currentTimeMillis();

    if (currentHour < hour) {
    // 延时时间 = 当天8点-当前时间
    String currentDay = format1.format(new Date());
    long currentDay8 = format2.parse(currentDay + " " + time).getTime();
    delayTime = currentDay8 - currentTime;
    } else if (currentHour == hour) {
        delayTime = 0;
    } else {
        // 延时时间 = 明天8点-当前时间
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, 1);
        String nextDay = format1.format(c.getTime());
        long nextDay8 = format2.parse(nextDay + " " + time).getTime();
        delayTime = nextDay8 - currentTime;
    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
        //TODO 执行任务
        }
    };

    Timer timer = new Timer(true);
    timer.schedule(task, delayTime, 24 * 60 * 60 * 1000);
    }

你可能感兴趣的:(java)