简体   繁体   中英

How do I make something stretch over a certain period of time

I'm trying to make an action "stretch" over a certain period of time, being 1 second.

public static int i = 0;
public static void click() {
    Robot robot;
    try {
        robot = new Robot();
        for (i = i; i < cps; i++) {
         robot.mousePress(InputEvent.BUTTON1_MASK);
         Random rn = new Random();
         int range = cps - 10 + 1;
         int randomNum =  rn.nextInt(range) + 10;
         robot.delay(randomNum);
         robot.mouseRelease(InputEvent.BUTTON1_MASK);
         i++;
        }
    if (i == cps) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        i = 0;
    }
    } catch (AWTException e) {
        e.printStackTrace();
    }

}

As you can see, this is the code for a "simple" auto clicker. It runs within this timer.

public static void getClick() {
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        while (enabled) {
            click();
        }
    }
}, 1, 1);
}

Is it in any way possible to make this action "stretch" it's action to 1 second. I really don't want it to click 12 times (Example), and then pause for 1 second. It'd be way nicer if these 12 clicks were "stretched" over that 1 second. Is it possible anyone can help me?

You could just let it sleeps for 1000ms/cps. If the user set cps=10 then 10 Thread.sleep(1000/cps) would let it click ten times in one sec. With cps=0.5 it would click once in two seconds.
(with a little discrepancy, because your code needs time to execute). And you should not create your random object in your loop.

Random rn = new Random();
while(true) {
     robot.mousePress(InputEvent.BUTTON1_MASK);
     int range = cps - 10 + 1;
     int randomNum =  rn.nextInt(range) + 10;
     robot.delay(randomNum);
     robot.mouseRelease(InputEvent.BUTTON1_MASK);
     i++;
     try {
        Thread.sleep(1000/cps);
     } catch (InterruptedException e) {
        e.printStackTrace();
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM