java: 지정된 초수 후에 함수를 실행합니다.
5초 후에 실행하고 싶은 기능이 있습니다.자바에서는 어떻게 하면 되나요?
javax.swing.timer를 찾았는데 사용법을 잘 모르겠어요.이 수업에서 제공하는 것보다 훨씬 더 간단한 것을 찾고 있는 것 같아요.
간단한 사용 예를 추가해 주세요.
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
}
},
5000
);
편집:
타이머 개체에 대한 마지막 라이브 참조가 사라지고 모든 미결 태스크 실행이 완료된 후 타이머의 태스크 실행 스레드는 정상적으로 종료되며 가비지 컬렉션의 대상이 됩니다.단, 이 작업은 임의로 오래 걸릴 수 있습니다.
다음과 같은 경우:
// When your program starts up
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// then, when you want to schedule a task
Runnable task = ....
executor.schedule(task, 5, TimeUnit.SECONDS);
// and finally, when your program wants to exit
executor.shutdown();
에는 다양한 공장 방법이 있습니다.Executor
대신 사용할 수 있습니다(수영장에 스레드를 더 넣으려면).
작업이 끝나면 실행자를 종료하는 것이 중요합니다.그shutdown()
method는 마지막 작업이 완료되면 스레드 풀을 완전히 셧다운하고 이 작업이 완료될 때까지 차단합니다. shutdownNow()
는 스레드 풀을 즉시 종료합니다.
사용 예javax.swing.Timer
Timer timer = new Timer(3000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// Code to be executed
}
});
timer.setRepeats(false); // Only execute once
timer.start(); // Go go go!
이 코드는 한 번만 실행되며 3000ms(3초) 후에 실행됩니다.
camickr가 언급한 바와 같이 간단한 소개를 위해 "How to Use Swing Timers"를 검색해야 합니다.
가비지 컬렉터가 스레드를 정리할 때까지 기다릴 수 없는 경우에는 실행 메서드가 종료될 때 타이머를 취소하십시오.
Timer t = new java.util.Timer();
t.schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
// close the thread
t.cancel();
}
},
5000
);
제 코드는 다음과 같습니다.
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here, and if you have to refresh UI put this code:
runOnUiThread(new Runnable() {
public void run() {
//your code
}
});
}
},
5000
);
원래 질문에는 "스윙 타이머"가 언급되어 있습니다.실제로 SWing에 관한 질문이 있는 경우 유틸리티가 아닌 스윙타이머를 사용해야 합니다타이머.
자세한 내용은 "타이머 사용 방법"에 대한 스윙 튜토리얼의 섹션을 참조하십시오.
스레드를 사용할 수 있습니다.sleep() 함수
Thread.sleep(4000);
myfunction();
4초 후에 기능이 실행됩니다.그러나 이 경우 전체 프로그램이 일시 중지될 수 있습니다.
다른 모든 불청객은 새 스레드 내에서 코드를 실행해야 합니다.단순한 사용 예에 따라서는 조금만 기다렸다가 동일한 스레드/플로우 내에서 실행을 계속할 수도 있습니다.
다음 코드는 이 기술을 보여줍니다.이는 java.util과 유사하다는 점에 유의하십시오.타이머는 후드 아래에서 작동하지만 더 가볍습니다.
import java.util.concurrent.TimeUnit;
public class DelaySample {
public static void main(String[] args) {
DelayUtil d = new DelayUtil();
System.out.println("started:"+ new Date());
d.delay(500);
System.out.println("half second after:"+ new Date());
d.delay(1, TimeUnit.MINUTES);
System.out.println("1 minute after:"+ new Date());
}
}
Delay Util 구현
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class DelayUtil {
/**
* Delays the current thread execution.
* The thread loses ownership of any monitors.
* Quits immediately if the thread is interrupted
*
* @param duration the time duration in milliseconds
*/
public void delay(final long durationInMillis) {
delay(durationInMillis, TimeUnit.MILLISECONDS);
}
/**
* @param duration the time duration in the given {@code sourceUnit}
* @param unit
*/
public void delay(final long duration, final TimeUnit unit) {
long currentTime = System.currentTimeMillis();
long deadline = currentTime+unit.toMillis(duration);
ReentrantLock lock = new ReentrantLock();
Condition waitCondition = lock.newCondition();
while ((deadline-currentTime)>0) {
try {
lock.lockInterruptibly();
waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} finally {
lock.unlock();
}
currentTime = System.currentTimeMillis();
}
}
}
ScheduledThreadPoolExecutor
이 능력은 있지만 꽤 무겁습니다.
Timer
에는 이 기능도 있지만 한 번만 사용해도 여러 개의 스레드가 열립니다.
다음은 테스트(Android의 Handler.postDelayed()에 가까운 서명)를 사용한 간단한 구현입니다.
public class JavaUtil {
public static void postDelayed(final Runnable runnable, final long delayMillis) {
final long requested = System.currentTimeMillis();
new Thread(new Runnable() {
@Override
public void run() {
// The while is just to ignore interruption.
while (true) {
try {
long leftToSleep = requested + delayMillis - System.currentTimeMillis();
if (leftToSleep > 0) {
Thread.sleep(leftToSleep);
}
break;
} catch (InterruptedException ignored) {
}
}
runnable.run();
}
}).start();
}
}
테스트:
@Test
public void testRunsOnlyOnce() throws InterruptedException {
long delay = 100;
int num = 0;
final AtomicInteger numAtomic = new AtomicInteger(num);
JavaUtil.postDelayed(new Runnable() {
@Override
public void run() {
numAtomic.incrementAndGet();
}
}, delay);
Assert.assertEquals(num, numAtomic.get());
Thread.sleep(delay + 10);
Assert.assertEquals(num + 1, numAtomic.get());
Thread.sleep(delay * 2);
Assert.assertEquals(num + 1, numAtomic.get());
}
public static Timer t;
public synchronized void startPollingTimer() {
if (t == null) {
TimerTask task = new TimerTask() {
@Override
public void run() {
//Do your work
}
};
t = new Timer();
t.scheduleAtFixedRate(task, 0, 1000);
}
}
이 경우 다음과 같이 생각합니다.
import javax.swing.*;
import java.awt.event.ActionListener;
최고입니다.질문이 Ui 스택을 방지하거나 부하가 높은 작업 또는 네트워크 호출 전에 진행 상황을 볼 수 없는 경우.(내 경험상) 다음과 같은 방법을 사용할 수 있습니다.
1초 후에 메서드를 실행합니다.
public static void startMethodAfterOneSeconds(Runnable runnable) {
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
runnable.run();
}
});
timer.setRepeats(false); // Only execute once
timer.start();
}
n초 후에 메서드를 1회 실행합니다(반복하지 않음):
public static void startMethodAfterNMilliseconds(Runnable runnable, int milliSeconds) {
Timer timer = new Timer(milliSeconds, new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
runnable.run();
}
});
timer.setRepeats(false); // Only execute once
timer.start();
}
n초 후에 메서드를 실행하고 다음을 반복합니다.
public static void repeatMethodAfterNMilliseconds(Runnable runnable, int milliSeconds) {
Timer timer = new Timer(milliSeconds, new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
runnable.run();
}
});
timer.setRepeats(true); // Only execute once
timer.start();
}
사용방법:
startMethodAfterNMilliseconds(new Runnable() {
@Override
public void run() {
// myMethod(); // Your method goes here.
}
}, 1000);
가장 투명한 방법은 Handler 클래스의 post Delayed 함수를 다음과 같이 사용하는 것입니다.
new Handler().postDelayed(this::function, 1000);
또는 다음과 같이 내부에 함수를 구현할 수 있습니다.
new Handler().postDelayed(() -> System.out.println("A second later"), 1000);
첫 번째 인수는 함수이고 두 번째 인수는 지연시간(밀리초)입니다.첫 번째 예에서 호출된 함수의 이름은 "함수"입니다.
언급URL : https://stackoverflow.com/questions/2258066/java-run-a-function-after-a-specific-number-of-seconds
'programing' 카테고리의 다른 글
여러 MySQL 행을 하나의 필드에 연결할 수 있습니까? (0) | 2022.10.02 |
---|---|
임의의 베이스에서 정수를 문자열로 변환하려면 어떻게 해야 합니까? (0) | 2022.10.02 |
따옴표와 괄호가 있는 경우와 없는 경우의 set Timeout의 차이 (0) | 2022.10.02 |
SQL: 행 순서 위치를 변경하는 방법 (0) | 2022.10.02 |
utf8_bin과 latin1_general_cs의 차이점은 무엇입니까? (0) | 2022.10.02 |