[英]How to call a method every s seconds
我想調用一個現有的方法,它會截取屏幕截圖並每隔 s 秒執行一次,具體取決於用戶的輸入。
如果不停止程序,怎么可能做到這一點?
編輯:我不想調用 function n 次或 s 秒后。 相反,我想每隔 s 秒運行一次,而不會導致程序停止。
在這種情況下,請使用“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);
根據您的描述, java 可能重復:在特定秒數后運行 function
根據您的標題,您可以使用遞歸調用它 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);
}
}
您可以創建一個接收 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.