title: How to run a task DURING PARTICULAR PERIOD OF TIME with ScheduledExecutorService?
body: <p>I am attempting to create a scheduled job which runs every 5 minutes from 7 AM to 22 PM everyday. For example, it should runs at 7:00, 7:05, 7:10 ... 21:55, and then it should stop at 22:00. On the next day, it runs the same schedule again and so on.</p>
  <p>I have found this example which shows how to use <code>ScheduledExecutorService</code> to start a task at particular time.
  <a href="https://stackoverflow.com/questions/20387881/how-to-run-certain-task-every-day-at-a-particular-time-using-scheduledexecutorse">How to run certain task every day at a particular time using ScheduledExecutorService?</a></p>
  <p>I referred to the answer and write my code like below:
  (I am using Java 7)</p>
  <pre><code>class Scheduler {
      private ScheduledExecutorService executors;
  
      public static void main(String[] arg) {
         Runnable task = new Runnable() {
              @Override
              public void run() {
                  ...DO SOMETHING...
              }
         };
          
         // Get how many seconds before the next start time (7AM).
         long initDelay = getInitialDelay(7); 
         
         ScheduledExecutorService executors = Executors.newSingleThreadScheduledExecutor();
         executors.scheduleAtFixedRate(task, initDelay, (60 * 5), TimeUnit.SECONDS);
     }
  
      private static long getInitialDelay(int hour) {
          Calendar calNow = Calendar.getInstance();
  
          Calendar cal = Calendar.getInstance();
          cal.set(Calendar.HOUR_OF_DAY, hour);
          cal.set(Calendar.MINUTE, 0);
          cal.set(Calendar.SECOND, 0);
  
          long diff = cal.getTimeInMillis() - calNow.getTimeInMillis();
          if (diff &lt; 0) {
              cal.add(Calendar.DAY_OF_MONTH, 1);
              diff = cal.getTimeInMillis() - calNow.getTimeInMillis();
          }
  
          return diff / 1000;
      }
  }
  </code></pre>
  <p>My above code starts at 7 AM and runs every 5 minutes perfectly. However, how can I do to control <code>ScheduledExecuterService</code> to stop the task at 22 PM and then start again at 7 AM on the next day?</p>
  <p>Or, is there any better other way to run a task during particular period of time everyday?</p>