【问题标题】:How to call a method every s seconds如何每隔 s 秒调用一次方法
【发布时间】:2020-03-12 19:18:24
【问题描述】:

我想调用一个现有的方法来截取屏幕截图并每隔 s 秒执行一次,具体取决于用户的输入。

如何在不停止程序的情况下做到这一点?

编辑:我不想调用一个函数 n 次,或者在 s 秒之后。相反,我想每隔 s 秒运行一次,而不会导致程序停止。

【问题讨论】:

标签: java timer repeat


【解决方案1】:

在这种情况下,请使用“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);

【讨论】:

  • 我实际上想每隔 n 秒调用一次该方法。标题有点误导,我的错。我已经改了。
【解决方案2】:

您可以创建一个接收 int(n 秒)的方法,然后在 Thread.sleep(n*1000) 之后执行 screenshot 方法。

public void screenShotWithTimer(int n){
    while(true){
        takeScreenShot();
        try{
            Thread.sleep(n*1000);
        }catch(InterruptedException e){}
    }
}
【解决方案3】:

根据您的描述,java: run a function after a specific number of seconds 可能重复

根据您的标题, 你可以使用递归调用它 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);
}
}

【讨论】:

    猜你喜欢
    • 2019-02-01
    • 2015-07-27
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2022-11-29
    相关资源
    最近更新 更多