简体   繁体   中英

How to run a task DURING PARTICULAR PERIOD OF TIME with ScheduledExecutorService?

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.

I have found this example which shows how to use ScheduledExecutorService to start a task at particular time. How to run certain task every day at a particular time using ScheduledExecutorService?

I referred to the answer and write my code like below: (I am using Java 7)

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 < 0) {
            cal.add(Calendar.DAY_OF_MONTH, 1);
            diff = cal.getTimeInMillis() - calNow.getTimeInMillis();
        }

        return diff / 1000;
    }
}

My above code starts at 7 AM and runs every 5 minutes perfectly. However, how can I do to control ScheduledExecuterService to stop the task at 22 PM and then start again at 7 AM on the next day?

Or, is there any better other way to run a task during particular period of time everyday?

A fixed scheduled executor service cannot alter its timing.

So use the single-run non-fixed scheduled executor service. Call ScheduledExecutorService::schedule . On its first run, check the current time. If before the end of the work day, call the same method schedule again, passing a delay of five minutes. If after the end of the work day, pass a delay of eight hours, the amount of time until the new work day starts.

So, a simple little trick. Each run of your runnable schedules the next run, endlessly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM