简体   繁体   中英

Scheduler for a task to run at particular hour of the day for every N days

I am looking for a scheduler which should run at a particular hour in the day for every N specified days.

For example, my task should run at 11PM for every 10 days.

The hour can be configured using cron expression, but how do we set the interval.

Thanks for the help

You can use java.util.concurrent.ScheduledExecutorService

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(command, getTonight10PM(), period, unit);

Update: To set the initialDelay, you can set the time in GregorianCalendar as 10 PM and pass it as an argument

private static Date getTonight10PM() {
        Calendar today = new GregorianCalendar();
        Calendar result =
            new GregorianCalendar(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE), 23, 0);
        return result.getTime();
}

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