javaschedulerexecutors

Executors Schedule in different intervals


I try to schedule a Executors with newSingleThreadScheduledExecutor that send a report after 10 days(from the initialized of the system), after 20 days(from the initialized of the system) and every 1st of the month. I tried to use newSingleThreadScheduledExecutor that runs every day and check if today is after 10 days.. 20 days and etc. But, I think we have a more elegant way to solve this with some executors. Do you have any idea how can I improve my code?

The scheduler:

   scheduler.scheduleWithFixedDelay(() -> {
        try {
            createReport();
        } catch (Exception e) {
            log.error("Error to create engagement report", e);
        }
    }, 1, 1, TimeUnit.DAYS);

and on the createReport function - I check the dates.

Thanks!


Solution

  • Eventually, I use ScheduledExecutorService schedule that initializing in the constructor:

    scheduler.schedule(createTask , nextDayOfTask, TimeUnit.DAYS);
    

    So, every time I get to the createTask - I re-calc when the next report should get out and update the schedule.

    public Runnable createTask = new Runnable() {
        @Override
        public void run() {
            // Do What Ever You Need 
            scheduler.schedule(this, nextDayOfTask, TimeUnit.DAYS);
        }
    };