简体   繁体   English

如何每隔 s 秒调用一次方法

[英]How to call a method every s seconds

I would like to call an existing method which takes a screenshot and execute it every s seconds, depending on the input of the user.我想调用一个现有的方法,它会截取屏幕截图并每隔 s 秒执行一次,具体取决于用户的输入。

How would it be possible to do that without stopping the program?如果不停止程序,怎么可能做到这一点?

Edit: I don't want to call a function n number of times, or after s seconds.编辑:我不想调用 function n 次或 s 秒后。 Rather, I would like to run it every s seconds without it causing the program to stop.相反,我想每隔 s 秒运行一次,而不会导致程序停止。

In that case, use "Timer and TimerTask Classes"在这种情况下,请使用“Timer 和 TimerTask 类”

import java.util.Timer;
import java.util.TimerTask;

/**
 * Simple demo that uses java.util.Timer to schedule a task 
 * to execute once 5 seconds have passed.
 */

public class Reminder {
    Timer timer;

    public Reminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    }

    class RemindTask extends TimerTask {
        public void run() {
            System.out.println("Time's up!");
            timer.cancel(); //Terminate the timer thread
        }
    }

    public static void main(String args[]) {
        new Reminder(5);
        System.out.println("Task scheduled.");
    }
}

........ The below answer was for the same question which was edited later on ........

In Java 8, You can do this to call a method n times:
But if you put it into a little helper function that takes a couple of parameters

IntStream.range(0, n).forEach(i -> doSomething());

void repeat(int count, Runnable action) {
    IntStream.range(0, count).forEach(i -> action.run());
}
This will enable you to do things like this:

repeat(3, () -> System.out.println("Hello!"));
and also this:

repeat(4, this::doSomething);

As per your description, it's possible duplicate of java: run a function after a specific number of seconds根据您的描述, java 可能重复:在特定秒数后运行 function

As per your title, you can use recursion to call it n number of times根据您的标题,您可以使用递归调用它 n 次

int number = 6; // can be anything as per user input
callMethod(number);

//methid implementation
void callMethod(int n) {
//do stuff
if (n>0)
{
callMethod(n-1);
}
}

You can create a method which will receive an int (n seconds) and then will execute the screenshot method after a Thread.sleep(n*1000).您可以创建一个接收 int(n 秒)的方法,然后在 Thread.sleep(n*1000) 之后执行屏幕截图方法。

public void screenShotWithTimer(int n){
    while(true){
        takeScreenShot();
        try{
            Thread.sleep(n*1000);
        }catch(InterruptedException e){}
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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