user12252748
user12252748

Reputation:

Wait/sleep until a specific time (e.g. Thursday at 10:59) in java

I’m currently using selenium in a web bot to purchase items on a website. When I search for the item I want to buy and it cannot be found I use driver.navigate().refresh() to refresh the page to see if it is there now, it will keep doing this until it finds the product when it is released on the page. However, I wish to start my bot a few hours before the release of the product which currently doesn’t work as after roughly 30 seconds of refreshing the page I get banned from the page due to the anti-ddos software they use. One option is to increase the delay between refreshing, however I need to catch the release of this product as soon as possible so I’m trying to find a way that my program can wait/sleep until 30 seconds before the release however I’m struggling to find a way to do this.

Upvotes: 0

Views: 1081

Answers (2)

Alex R
Alex R

Reputation: 3311

Just call Thread.sleep with the appropriate amount of milliseconds:

public static void main(String[] args) throws InterruptedException {
    long currentTime = System.currentTimeMillis();
    long releaseTime = currentTime + 1000 * 60 * 60 * 24 * 3; // 3 days

    Thread.sleep(releaseTime - currentTime);
}

Another way would be to use java.time classes:

public static void main(String[] args) throws InterruptedException {
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime release = LocalDateTime.of(2019, 10, 30, 13, 30);

    long sleepDuration = Duration.between(now, release).toMillis();
    TimeUnit.MILLISECONDS.sleep(sleepDuration);
}

Java 9 introduces new methods to the Duration class like toSeconds(), toMinutes() and so on.

You could also consider using a ScheduledExecutorService to schedule your tasks. This is especially useful if you have multiple tasks to schedule and don't want having multiple threads being blocked for that:

private static final ScheduledExecutorService service = new ScheduledThreadPoolExecutor(2);

private static ScheduledFuture<?> scheduleTask(Runnable task, LocalDateTime releaseTime) {
    Duration duration = Duration.between(LocalDateTime.now(), releaseTime);
    return service.schedule(task, duration.toSeconds(), TimeUnit.SECONDS);
}

In general, to sleep until the next Thursday at 10:59 you could use the following code:

LocalDateTime release = LocalDateTime.now()
            .with(TemporalAdjusters.nextOrSame(DayOfWeek.THURSDAY))
            .withHour(10)
            .withMinute(59);

Duration duration = Duration.between(LocalDateTime.now(), release);
TimeUnit.MILLISECONDS.sleep(duration.toMillis());

Upvotes: 2

davesbrain
davesbrain

Reputation: 606

I think rather than sleeping you should take a look at scheduled tasks with cron expressions in Spring... that way you don't have a blocked thread just sitting there.

Scheduled Tasks with Spring
Cron Expressions

Upvotes: 1

Related Questions