2 回答

TA貢獻1785條經驗 獲得超8個贊
無需進入線程和計時器等的簡單方法是在調用方法時獲取當前時間并存儲它。在下一次呼叫中,您將新的當前時間與舊時間進行比較。如果 5 秒未過去,則不執行任何操作。
例如:
long lastCall = 0;
void doSomething()
{
long now = secondsSinceEpoch();
if (lastCall == 0 || now-lastCall > 5)
{
// Do stuff
// lastCall = now
}
}

TA貢獻1830條經驗 獲得超3個贊
我不知道這是否能幫助你。
private long timeMillions = 0;
public void doSomething(){
// if within 5 seconds
if(System.currentTimeMillis() < timeMillions + 5 * 1000){
//retrun or do some thing else
return;
}else{
// after 5 seconds
timeMillions = System.currentTimeMillis();
System.out.println("do something");
}
}
添加回答
舉報