Executors Schedule in different intervals

103 views Asked by At

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!

1

There are 1 answers

0
Nofar103 On BEST ANSWER

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);
    }
};