Java:我如何在每周星期日上午12:01重复运行函数?

Java:我如何在每周星期日上午12:01重复运行函数?,java,function,call,thread-sleep,Java,Function,Call,Thread Sleep,如何在停机/停机期间使用最少CPU的情况下,每周周日12:01重复运行函数Thread.sleep()?使用Spring框架中的@Scheduled注释。每周周日上午12:01的cron表达式为:10**0 @已计划(cron=“1 0**0”) 公共无效剂量测定法(){ //每周执行一次的事情 }可能重复使用cron use import java.util.Calendar; import java.util.Date; import java.util.Locale; import jav

如何在停机/停机期间使用最少CPU的情况下,每周周日12:01重复运行函数
Thread.sleep()

使用Spring框架中的@Scheduled注释。每周周日上午12:01的cron表达式为:
10**0

@已计划(cron=“1 0**0”) 公共无效剂量测定法(){ //每周执行一次的事情 }

可能重复使用cron use
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));
  }

}