java定时每天指定时间执行任务

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

方法调用

try {
    // 每天8点执行定时任务
    timing("08:00:00");
} catch (ParseException e) {
    e.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值