Dies ist eine Möglichkeit, es mit dem java.utils Paket tun:
public class Main {
private static final int delayMilliseconds = 20000; // 20 seconds
private static Timer timer;
public static void main(String[] args) throws Exception{
System.out.println("START");
// Create a Timer
timer = new Timer();
doTask();
Thread.sleep(1000);
doTask();
Thread.sleep(1000);
doTask();
Thread.sleep(1000);
doTask();
Thread.sleep(1000);
System.out.println("END");
}
public static final void doTask(){
System.out.println("Started at: " + Calendar.getInstance().getTime());
System.out.println("Perform your task here");
// Create new task
TimerTask task = new TimerTask() {
@Override
public void run() {
// Run the "timeout finished" function here.
System.out.println("Timed out! " + Calendar.getInstance().getTime());
}
};
// Schedule a task for in 20 seconds in the future.
timer.schedule(task, delayMilliseconds);
}
}
Wenn Sie Java verwendet habe 8 vor (oder möchten, es benutzen), könnten Sie stattdessen mit diesem Code versuchen:
public class Main {
private static final int delayMilliseconds = 20000; // 20 seconds
private static Timer timer;
public static void main(String[] args) throws Exception{
System.out.println("START");
// Create a Timer
timer = new Timer();
doTask(() -> System.out.println("Task 1"));
Thread.sleep(1000);
doTask(() -> System.out.println("Task 2, starting a second later"));
Thread.sleep(1000);
doTask(() -> System.out.println("Task 3, starting a second later"));
Thread.sleep(1000);
doTask(() -> System.out.println("Task 4, starting a second later"));
Thread.sleep(1000);
System.out.println("END");
}
public static final void doTask(Runnable function) throws Exception{
System.out.println("Started at: " + Calendar.getInstance().getTime());
// Run the function here
function.run();
// Create new task
TimerTask task = new TimerTask() {
@Override
public void run() {
// Run the "timeout finished" function here.
System.out.println("Timed out! " + Calendar.getInstance().getTime());
}
};
// Schedule a task for in 20 seconds in the future.
timer.schedule(task, delayMilliseconds);
}
}
die zweite Methode ist es, so dass Sie eine Funktion für die doTask()
Funktion übergeben können. Schauen Sie sich this link für weitere Informationen über die Timer-Klasse und sehen Sie this link für weitere Informationen über Lambdas in Java 8. :)