6

Javaで特定の時間にタスクをスケジュールできるようにしたいと思います。は定期的な間隔で、指定された遅延の後にスケジュールする機能があることを理解していExecutorServiceますが、一定期間後ではなく、時間帯を探しています。

たとえば、Runnable2:00に実行する方法はありますか、それとも今から2:00までの時間を計算し、その遅延の後に実行するようにランナブルをスケジュールする必要がありますか?

4

6 に答える 6

6

春の注釈も使用できます

@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
// something that should execute on weekdays only
}

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

于 2011-11-09T15:36:56.283 に答える
5

これは、java7SEを使用して解決した方法です:

    timer = new Timer("Timer", true);
    Calendar cr = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    cr.setTimeInMillis(System.currentTimeMillis());
    long day = TimeUnit.DAYS.toMillis(1);
    //Pay attention - Calendar.HOUR_OF_DAY for 24h day model 
    //(Calendar.HOUR is 12h model, with p.m. a.m. )
    cr.set(Calendar.HOUR_OF_DAY, it.getHours());
    cr.set(Calendar.MINUTE, it.getMinutes());
    long delay = cr.getTimeInMillis() - System.currentTimeMillis();
    //insurance for case then time of task is before time of schedule
    long adjustedDelay = (delay > 0 ? delay : day + delay);
    timer.scheduleAtFixedRate(new StartReportTimerTask(it), adjustedDelay, day);
    //you can use this schedule instead is sure your time is after current time
    //timer.scheduleAtFixedRate(new StartReportTimerTask(it), cr.getTime(), day);

正しくやると思ったよりもトリッキーです

于 2012-09-07T07:23:57.080 に答える
4

あなたはQuartzが欲しくなるでしょう。

于 2011-11-09T14:05:44.540 に答える
2

今朝この状況に陥りました...これは真夜中に実行する私のコードでした

    scheduler = Executors.newScheduledThreadPool(1);
    Long midnight=LocalDateTime.now().until(LocalDate.now().plusDays(1).atStartOfDay(), ChronoUnit.MINUTES);
    scheduler.scheduleAtFixedRate(this, midnight, 1440,  TimeUnit.MINUTES);
于 2014-08-04T13:41:54.240 に答える
0

Quartzをチェックしてください。プロダクションアプリに使用していて、とても良いです。crontabとほとんど同じように機能します。設定されたスケジュールの時間を指定すると、その時間にコールバックが実行されます。

于 2011-11-09T14:06:44.473 に答える
0

ユーザーjava.util.Timer。新しいメソッドschedule(task, time)があります。ここで、timeは、タスクを1回実行する日付です。

于 2011-11-09T14:07:26.620 に答える