我在一小时内每隔16分钟执行一次工作(3次运行)。这项工作将在过去16点,过去32点和过去48点运行。它不会溢出到下一个小时。
以下是两小时窗口的运行示例:
Run 1:
Thu Jul 04 06:16:00 EDT 2013
Run 2:
Thu Jul 04 06:32:00 EDT 2013
Run 3:
Thu Jul 04 06:48:00 EDT 2013
Run 4:
Thu Jul 04 07:16:00 EDT 2013
Run 5:
Thu Jul 04 07:32:00 EDT 2013
Run 6:
Thu Jul 04 07:48:00 EDT 2013
我的问题是我需要为每个工作建立一些目标(不重要),但最终我决定确定当天要运行多少个工作,然后为每个工作设定目标
我正在研究逻辑,以确定在给定可变开始时间的情况下每天运行的次数。我尝试用一些计算来做这件事,但最终依赖于这段代码,它使用日历来计算当天剩下多少次运行:
public int getRunsLeftInDay(int runIntervalMinutes, int offset){
/*
Offset is when the job starts
Currently runIntervalMinutes = 16 && offset = 16
So start 16 minutes after the hour and run on 16 minute interval
*/
/*
This method is tested returns proper next run date, basically gives
the next 16 past || 32 past || 48 past time that will occur
*/
Date nextRunDt = this.getNextRun(runIntervalMinutes, offset);
//Determine last run per hour
int lastRunMinute = (60/runIntervalMinutes) * runIntervalMinutes;
int runCount = 0;
Calendar cal = Calendar.getInstance();
cal.setTime(nextRunDt);
int currentDay = cal.get(Calendar.DAY_OF_YEAR);
while(cal.get(Calendar.DAY_OF_YEAR) == currentDay){
runCount++; //count first run since calendar is set to nextRunDt
if(cal.get(Calendar.MINUTE) == lastRunMinute){
cal.add(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, offset);
}else{
cal.add(Calendar.MINUTE, runIntervalMinutes);
}
}
return runCount;
}
目前我的代码正在返回正确的运行量,但我想探索是否有更好的方法来确定此值(通过某些日期计算)。
基本上我有两个问题:
1。这种查找每天运行量的方法是否足够?
2。我如何使用日期/时间计算?
答案 0 :(得分:0)
当天剩余的跑步次数是当前小时剩余的跑步次数加上当天三次剩余的小时数。或者,我是否误解了这个问题?
答案 1 :(得分:0)
你应该避免使用while循环,否则我认为效率不重要。根据我的经验,Date
对象更难以处理。 (尚未测试)
Calendar now = Calendar.getInstance(),
soon = Calendar.getInstance(),
midnight = Calendar.getInstance();
soon.add(Calendar.HOUR, 1);
soon.set(Calendar.MINUTE, 0);
soon.set(Calendar.SECOND, 0);
midnight.add(Calendar.DAY, 1);
midnight.set(Calendar.HOUR, 0);
midnight.set(Calendar.MINUTE, 0);
midnight.set(Calendar.SECOND, 0);
int times_left_this_hour = (soon.getTimeInMillis() - now.getTimeInMillis()) / 1000 / 60 / 16;
int times_left_this_day = (midnight.getTimeInMillis() - soon.getTimeInMillis()) / 1000 / 60 / 60 * 3;