![](/img/trans.png)
[英]How to run certain task every day at a particular time using ScheduledExecutorService?
[英]How to run a particular task after 7 PM on Thursday using ScheduledExecutorsService?
我正在嘗試安排一項工作,該工作要在每個星期四晚上7點以后進行。 但是到目前為止,使用以下代碼,我可以使其在周四運行,但不能在晚上7點之后運行。
我為此使用ScheduledExecutorsService
。 有什么辦法可以讓它在星期四晚上7點之后運行?
private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
final ArrayList<Callable<Void>> tasks = Lists.newArrayList(new TestBImpl(), new TestAImpl());
Calendar with = Calendar.getInstance();
Map<Integer, Integer> dayToDelay = new HashMap<Integer, Integer>();
dayToDelay.put(Calendar.FRIDAY, 0);
dayToDelay.put(Calendar.SATURDAY, 6);
dayToDelay.put(Calendar.SUNDAY, 5);
dayToDelay.put(Calendar.MONDAY, 4);
dayToDelay.put(Calendar.TUESDAY, 3);
dayToDelay.put(Calendar.WEDNESDAY, 2);
dayToDelay.put(Calendar.THURSDAY, 1);
int dayOfWeek = with.get(Calendar.DAY_OF_WEEK);
int delayInDays = dayToDelay.get(dayOfWeek);
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
executorService.invokeAll(tasks);
} catch (Exception ex) {
ex.printStackTrace(); // or loggger would be better
}
}
}, 0, delayInDays, TimeUnit.DAYS);
任何建議都會有很大幫助。 我需要使用多線程方式來執行任務。 在我的tasks
,我將有兩個以上的類,而現在只有兩個類可以並行執行。
我將使調度程序在每個小時運行一次,該任務將使用日歷來確定日期和小時,並且僅在星期四晚上7點執行
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
Calendar c = Calendar.getInstance();
if (c.get(Calendar.HOUR_OF_DAY) == 19 && c.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
try {
executorService.invokeAll(tasks);
} catch (Exception ex) {
ex.printStackTrace(); // or loggger would be better
}
}
}
}, 0, 1, TimeUnit.HOURS);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.