[Play 2.6 - Java] Schedule at the same hour each day


#1

I’ve to schedule a check that sends an email at the same hour each day. Is there a way to do that in Play?


(Aditya Athalye) #2

Create an Akka Actor using the ActorSystem, and use its scheduler.

final ActorRef actor = actorSystem.actorOf(<props>);
actorSystem.scheduler().schedule(Duration.Zero, new Duration(86400, TimeUnit.SECONDS, actor.....)

(Adam Lane) #3

If your environment is load balanced one option is to create a AWS Lambda (easy to schedule) that hits a url to trigger the event.


#4

Ok, but when start the scheduler? I tried the following

this.actorSystem.scheduler().schedule(
                Duration.create(10, TimeUnit.SECONDS), // initialDelay
                Duration.create(1, TimeUnit.DAYS), // interval
                () -> checkForRefill(),
                this.executionContext
        );

but it starts now and the first trigger is next day at the same hour. But if I want to start at 1:00AM (e.g.) I’ve to start Play at 1:00AM.


#5

My environment isn’t load balanced. Sorry.


(Aditya Athalye) #6

You would need to calculate the time diff between 1.00 AM and the time the scheduler executes first time in seconds and that would be your initial delay represented as FiniteDuration.


#7

Thanks, if I do:

private void initialize() {
        LocalDateTime now  = LocalDateTime.now();
        Integer year = now.getYear();
        Integer month = now.getMonthValue();
        Integer day = now.getDayOfMonth();
        LocalDateTime tomorrow = LocalDateTime.of(year, month, day+1,1, 01,00 );
        Long hours = now.until(tomorrow, ChronoUnit.HOURS);
        this.actorSystem.scheduler().schedule(
                Duration.create(10, TimeUnit.SECONDS), // initialDelay
                Duration.create(1, TimeUnit.DAYS), // interval
                () -> checkForRefill(),
                this.executionContext
        );
    }

in hours I’ve the diff time, where I’ve to put it, in interval or initial delay?


(Aditya Athalye) #8

Initial Delay. The interval is 24 hours anyway right? So it the initial execution happens at 1.00 AM, subseqeunt executions would happen at the same time every day.


#9

Ok, thanks.