0

我在一小时内每 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. 我将如何使用日期/时间计算来做到这一点?

4

2 回答 2

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;
于 2013-07-04T13:59:16.393 回答
0

当天剩余的跑步次数是当前小时剩余的跑步次数加上当天剩余的小时数乘以三。或者,我误解了这个问题吗?

于 2013-07-04T11:49:04.913 回答