欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

定时任务scheduleAtFixedRate设定每天某个时刻执行

发布时间:2024/10/8 40 豆豆
生活随笔 收集整理的这篇文章主要介绍了 定时任务scheduleAtFixedRate设定每天某个时刻执行 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

使用下面这个定时任务方法实现

ScheduledFuture<?> java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

Parameters : command the task to executeinitialDelay the time to delay first executionperiod the period between successive executionsunit the time unit of the initialDelay and period parameters
Returns : a ScheduledFuture representing pending completion ofthe task, and whose get() method will throw anexception upon cancellation
Throws : RejectedExecutionException - if the task cannot bescheduled for executionNullPointerException - if command is nullIllegalArgumentException - if period less than or equal to zero
 

/** 获取指定时间对应的毫秒数* @param time "HH:mm:ss"* @return*/private long getTimeMillis(String time) {try {DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);return curDate.getTime();} catch (Exception e) {logger.error("getTimeMillis error:", e);}return 0;}

public void execute() {long oneDay = 24 * 60 * 60 * 1000;long initDelay = getTimeMillis("05:00:00") - System.currentTimeMillis();initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;executorService.scheduleAtFixedRate(task, initDelay, oneDay, TimeUnit.MILLISECONDS); }

总结

以上是生活随笔为你收集整理的定时任务scheduleAtFixedRate设定每天某个时刻执行的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。