JavaFX pausing during for loop WITHOUT using Thread.Sleep()


Question

I'm coding this in JavaFX using a FXMLController and the scene builder. I'm currently creating an Instagram "liker" mostly just for practice as I'm a Computer Science major, and I just like coding.

My issue is, I have a for loop that "likes" 20 photos for each hashtag, I obviously need a delay or I'd get banned rather quickly. The user can choose the delay, then I randomize this delay so it's not too robotic.

The only way I've been able to use this delay is through the thread.sleep method, but since I'm coding on the FXMLController, it freezes the whole UI, and somehow stops other textareas from being updated. This is obviously not ideal.

I've looked everywhere trying to find an alternative to this, but I can't find anything that works in my program.

I'll give the whole method:

    private void start() {
    sleepWhen();
    tagNumber++;
    int delays = Integer.valueOf(delay.getText());
    delays = delays * 1000;
    if (loaded) {
        runTime.clear();
        runTime.appendText("Liking...");
        for (int i = 0; i < 20; i++) {
            webEngine.executeScript("document.getElementsByClassName('btn btn-default btn-xs likeButton')[" + i + "].click()");
            try {
                double random = Math.random() * 1000;
                random = random + delays;
                delays = (int) random;
                System.out.println(delays);
                likes++;
                likesNumber.clear();
                likesNumber.appendText(String.valueOf(likes));
                System.out.println(String.valueOf(likes));
                Thread.sleep(delays);
                delays = Integer.valueOf(delay.getText());
                delays = delays * 1000;

            } catch (InterruptedException ex) {
                //do nothing
            }

            System.out.println("tag number" + tagNumber + "numbertags" + numberTags);
            if (!sleep) {
                if (tagNumber < numberTags) {
                    System.out.println("Loading tag:" + tagNumber);
                    loadTag(tagNumber);
                }
            }
        }
    }
}

This likes 20 photos, then loads another hashtag, and repeats.

Any help with this would be great, thanks.

1
1
5/28/2014 7:40:23 PM

Accepted Answer

The freeze is because you are trying to do everything on the same thread, when you are using Thread.sleep(delays), you are actually putting your UI thread to sleep and hence the lag !

Try using different thread for your work, you can either use a worker thread, if whatever you are doing will not affect the UI

or you can use Platform.runLater(), if you want the changes to shown on the UI !

For more details :

  1. concurrency in javafx !

  2. Platform.runLater and Task in JavaFX

2
5/23/2017 11:57:14 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon