【问题标题】:Java: How do I run function repeatedly every week Sunday at 12:01 AM?Java:如何在每周日凌晨 12:01 重复运行函数?
【发布时间】:2013-07-01 21:07:05
【问题描述】:

如何在每周日凌晨 12:01 重复运行一个函数,同时在停机/关闭时间使用最少的 CPU? Thread.sleep()?

【问题讨论】:

标签: java function call thread-sleep


【解决方案1】:

使用 Spring 框架中的 @Scheduled 注解。每周日凌晨 12:01 的 cron 表达式为:1 0 * * 0

    @Scheduled(cron="1 0 * * 0")
    public void doSomething() {
        // something that execute once a week
    }

【讨论】:

    【解决方案2】:
    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));
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-12
      • 1970-01-01
      • 2015-12-29
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      相关资源
      最近更新 更多