[英]Java: How do I run function repeatedly every week Sunday at 12:01 AM?
如何在每周的周日凌晨12:01重復運行功能,同時在停機時間/關機時間內使用最少的CPU? Thread.sleep()
嗎?
使用Spring框架中的@Scheduled批注。 每個星期天的上午12:01的cron表達式是: 1 0 * * 0
@Scheduled(cron =“ 1 0 * * 0”)public void doSomething(){//每周執行一次的事物}
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
class SundayRunner implements Runnable
{
private final Runnable target;
private final ScheduledExecutorService worker;
private volatile Date now;
SundayRunner(Runnable target, ScheduledExecutorService worker) {
this.target = target;
this.worker = worker;
}
@Override
public final void run()
{
if (now == null)
now = new Date();
else
target.run();
Date next = next(now);
long delay = next.getTime() - now.getTime();
now = next;
worker.schedule(this, delay, TimeUnit.MILLISECONDS);
}
Date next(Date now)
{
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(now);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date sunday;
for (sunday = cal.getTime(); sunday.before(now); sunday = cal.getTime())
cal.add(Calendar.DATE, 7);
return sunday;
}
public static void main(String... argv)
{
ScheduledExecutorService worker =
Executors.newSingleThreadScheduledExecutor();
Runnable job = new Runnable() {
@Override
public void run()
{
System.out.printf("The time is now %tc.%n", new Date());
}
};
worker.submit(new SundayRunner(job, worker));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.