我正在开发一种服务,假设每个小时的开始时间(1:00 PM,2:00 PM,3:00 PM等)都是正确的.
我尝试以下,但它有一个问题,我第一次必须在开始时运行程序,然后这个调度程序将重复.
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleWithFixedDelay(new MyTask(),1,TimeUnit.HOURS);
任何建议重复我的任务,不管我运行程序?
问候,
伊姆兰
解决方法
我也建议
Quartz这个.但是,上述代码可以使用initialDelay参数在小时开始时运行.
Calendar calendar = Calendar.getInstance(); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new MyTask(),millisToNextHour(calendar),60*60*1000,TimeUnit.MILLISECONDS); private static long millisToNextHour(Calendar calendar) { int minutes = calendar.get(Calendar.MINUTE); int seconds = calendar.get(Calendar.SECOND); int millis = calendar.get(Calendar.MILLISECOND); int minutesToNextHour = 60 - minutes; int secondsToNextHour = 60 - seconds; int millisToNextHour = 1000 - millis; return minutesToNextHour*60*1000 + secondsToNextHour*1000 + millisToNextHour; }