how to call a method after a time interval?
e.g if want to print a statement on screen after 2 second, what is its procedure?
System.out.println("Printing statement after every 2 seconds");
The answer is using the javax.swing.Timer and java.util.Timer together:
private static javax.swing.Timer t;
public static void main(String[] args) {
t = null;
t = new Timer(2000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Printing statement after every 2 seconds");
//t.stop(); // if you want only one print uncomment this line
}
});
java.util.Timer tt = new java.util.Timer(false);
tt.schedule(new TimerTask() {
#Override
public void run() {
t.start();
}
}, 0);
}
Obviously you can achieve the printing intervals of 2 seconds with the use of java.util.Timer only, but if you want to stop it after one printing it would be difficult somehow.
Also do not mix threads in your code while you can do it without threads!
Hope this would be helpful!
Create a Class:
class SayHello extends TimerTask {
public void run() {
System.out.println("Printing statement after every 2 seconds");
}
}
Call the same from your main method:
public class sample {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new SayHello(), 2000, 2000);
}
}
It can be achieved using Timer class
new Timer().scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
System.out.println("print after every 5 seconds");
}
},0,5000);
**You Must try this code. It works for me. **
Use Visual Studio and create Main.java file then paste this code and right click mouse>run java
`public class Main {
public static void main(String[] args) {
for (int i = 0; i <= 12; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
`
Related
package timerrr;
import java.util.*;
public class Timerrr {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(
new TimerTask() {
int i = 0;
#Override
public void run() {
System.out.println("timer is still running");
}
},
1 * 150 * 100,
1 * 50 * 100);
}
}
in your overridden run method increment i and if i = 5 cancel the timer:
timer.schedule(new TimerTask() {
int i = 0;
#Override
public void run() {
i++;
if(i==5) {
this.cancel();
}
else {
//YOUR CODE HERE
}
}
}, startDelay, fixedDelay);
Here should be an easier way to do what you want:
Calling the Thread.sleep(); method is, for some reason, one of my favorite things to call. You just have to surround it in a try/catch block like so:
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
System.out.println("timer is still running");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
You may want to put that it it's own method with it's own thread, so that you can have other things running while this is happening.
Hope this helped :)
Hello I'm trying to figure out a way in which my main thread return's a value every 1/10th or 1/n second for example...
public class MainGameLoop {
public static void main(String[] args) {
while (!Display.isCloseRequested()) {
//Run Game Logic
//every 1/10th second update skeletal animation
//ever 1/30th second update texture animation
}
}
I've been experimenting with seperate threads like this
public class HelloRunnable implements Runnable {
public void run() {
try{
Thread.sleep(500)
System.out.println("Hello from a thread!");
catch(Exectpion e) {
}
}
but the sleep effects my main thread's thread. If I sleep for 10 seconds, my mainthread sleeps for 10 seconds.
I've tried
Runnable z = new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hi");
}
};
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(z);
while (!Display.isCloseRequested()) {
//Run Game logic
}
}
This only runs once at initialization and delay's the "hi" after the specified sleep amount, alternatively this
Runnable z = new Runnable() {
public void run() {
try {
Thread.sleep(100000);
}catch(Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hi");
}
};
ExecutorService executor = Executors.newCachedThreadPool();
while (!Display.isCloseRequested()) {
//Run Game logic
executor.submit(z);
}
}
prints out "hi" as fast as the main thread can refresh.
public class TimerDemo extends TimerTask
{
public static void main(String[] args)
{
TimerTask tasknew = new TimerDemo();
Timer timer = new Timer();
timer.scheduleAtFixedRate(tasknew, 0, 1000);
}
#Override
public void run()
{
System.out.println("once every 1000 ms");
}
}
All of the tasks run on the same thread. In the above example if run() takes longer than 1000 ms to execute, the next scheduled execution will be delayed. See the javadocs for more details. If you want multiple threads use a ScheduledThreadPoolExecutor instead.
We want to schedule a java process to run till a specific time interval. Currently I am thinking to using TimerTask to schedule this process. In the start of every loop, will check the current time and then compare with the given time and stop the process if the time is elapsed.
Our code is something like below:
import java.util.Timer;
import java.util.TimerTask;
public class Scheduler extends TimerTask{
public void run(){
//compare with a given time, with getCurrentTime , and do a System.exit(0);
System.out.println("Output");
}
public static void main(String[] args) {
Scheduler scheduler = new Scheduler();
Timer timer = new Timer();
timer.scheduleAtFixedRate(scheduler, 0, 1000);
}
}
Is there a better approach for this?
Instead of checking if the time limit has been reached in every single iteration you could schedule another task for the said time limit and call cancel on your timer.
Depending on the complexity you might consider using a ScheduledExecutorService such as ScheduledThreadPoolExecutor. See in this answer when and why.
Simple working example with timer:
public class App {
public static void main(String[] args) {
final Timer timer = new Timer();
Timer stopTaskTimer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
System.out.println("Output");
}
};
TimerTask stopTask = new TimerTask() {
#Override
public void run() {
timer.cancel();
}
};
//schedule your repetitive task
timer.scheduleAtFixedRate(task, 0, 1000);
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2015-06-09 14:06:30");
//schedule when to stop it
stopTaskTimer.schedule(stopTask, date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
You can use RxJava, a very powerful library for reactive programming.
Observable t = Observable.timer(0, 1000, TimeUnit.MILLISECONDS);
t.subscribe(new Action1() {
#Override
public void call(Object o) {
System.out.println("Hi "+o);
}
}
) ;
try {
Thread.sleep(10000);
}catch(Exception e){ }
You can even use the lambda syntax:
Observable t = Observable.timer(0, 1000, TimeUnit.MILLISECONDS);
t.forEach(it -> System.out.println("Hi " + it));
try {
Thread.sleep(10000);
}catch(Exception e){ }
I am developing a system which has to start a task (download a file) regularly every N seconds. This is not a problem I did it using Timerand Timertaskas follows:
FileTimer rXMLFileTimer;
private static Timer timer = new Timer("FileReader");
rXMLFileTimer = new ReadFileTimer();
int myDelay = 30;
timer.scheduleAtFixedRate(rXMLFileTimer, 0, myDelay * 1000);
and the timertask will run until rXMLFileTimer.cancel() is called. Up to now no problem.
Now, It has been required that this timertask should run until the rXMLFileTimer.cancel() is called or a given amount of time.
My first approach (which didn't work) was to implement a Futureas follows:
public class Test {
public static class MyJob implements Callable<ReadFileTimer> {
#Override
public ReadFileTimer call() throws Exception {
Timer timer = new Timer("test");
ReadFileTimer t = new ReadFileTimer();
int delay = 10;
// Delay in seconds
timer.schedule(t, 0, delay * 1000);
return t;
}
}
public static void main(String[] args) {
MyJob job = new MyJob();
System.out.println(new Date());
Future<ReadFileTimer> control = Executors.newSingleThreadExecutor().submit(job);
ReadFileTimer timerTask = null;
try {
int maxAmountOfTime = 30;
timerTask = control.get(maxAmountOfTime, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
control.cancel(true);
} catch (InterruptedException ex) {
} catch (ExecutionException ex) {}
}
}
This is not working because I cannot call timerTask.cancel() after the timeout has happen. Then my question is: How can I start a timerTaskfor a given amount of time?
Thanks!
Why not just throw in a second timer task to cancel the first? For example, this code prints the date every second for ten seconds:
public static void main(String[] args) throws Exception {
Timer timer = new Timer();
final TimerTask runUntilCancelledTask = new TimerTask() {
#Override
public void run() {
System.out.println(new Date());
}
};
timer.schedule(runUntilCancelledTask, 0, 1000);
timer.schedule(new TimerTask() {
#Override
public void run() {
runUntilCancelledTask.cancel();
}
}, 10000); // Run once after delay to cancel the first task
}
I have a Jframe which is my application's window (appFrame in the following code) that contains a lot of logic and takes like 1 second or so to load. In the meantime I want to show my user a very nice loading frame (initFrame). However, when I run this code, the initFrame does appear but the text in a JLabel on it doesn't appear immediately - it actually doesn't appear at all in the brief moment till the app frame is loaded.
If i comment out all the appFrame, and only launch the initFrame, the text is loaded instantly, no waiting time at all. Why is this so? Might this be a concurrency issue?
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() { //as per best practice for concurrency in swing - see http://docs.oracle.com/javase/tutorial/uiswing/concurrency/
#Override
public void run() {
final JFrame initFrame = new InitFrame();
initFrame.setVisible(true);
final AppFrame appFrame = new AppFrame();
appFrame.setVisible(true);
initFrame.setVisible(false);
initFrame.dispose();
}
});
}
I would separate the frames' creation into two threads. The first, initializing InitFrame. Running this thread and calling isShowing() on the InitFrame object. When it returns true, run the second thread to initialize and show AppFrame.
This will force a happens before relationship between the visibility of the two frames.
class Main {
JFrame initFrame = null;
AppFrame appFrame = null;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initFrame = new InitFrame();
initFrame.setVisible(true);
}
});
while(!initFrame.isShowing()) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
appFrame = new AppFrame();
appFrame.setVisible(true);
initFrame.setVisible(false);
initFrame.dispose();
}
});
}
}
Here's an example of what might be going wrong in your AppFrame.
You can run the test with threading:
java SplashTest true
or without
java SplashTest
When threading is enabled, you see the SplashFrame and AppFrame updating every 250ms, more or less.
When threading is not enabled, you get to see the SplashFrame with no components showing, the app 'hangs' for 4 seconds, then you see the AppFrame.
The example is somewhat contrived, but might give you some ideas.
Note that the SplashFrame has no 'direct' connection to the AppFrame. All communication is through the AppFrameWorkListener interface.
I've also put the 'work' in the AppFrame. But really if there is a lot of processing to be done it should be extracted out of the UI code, run in a separate Thread, and the AppFrame would be notified of progress by the task, in the same way as the SplashFrame currently is.
import javax.swing.*;
class SplashTest {
static boolean useThread = false;
public static void main(String[] args) {
// Pass true at the command line to turn on threading.
// No args, or any value other than true will turn off threading.
if (args.length > 0) {
useThread = new Boolean(args[0]);
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SplashFrame splashFrame = new SplashFrame();
splashFrame.setVisible(true);
new AppFrame(splashFrame).setVisible(true);
}});
}
private static class BaseFrame extends JFrame {
public BaseFrame() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(200, 200);
setTitle(getClass().getSimpleName());
}
}
private static class SplashFrame extends BaseFrame implements AppFrameWorkListener {
JLabel status;
public SplashFrame() {
setLocation(0, 0);
status = new JLabel("Splash Frame");
getContentPane().add(status);
}
public void appFrameWorkStart() {
status.setText("Work started");
}
public void appFrameWorkProgress(long timeElapsed) {
status.setText("Work has taken " + timeElapsed + "ms so far");
}
public void appFrameWorkDone() {
// http://stackoverflow.com/questions/1234912/how-to-programmatically-close-a-jframe
setVisible(false);
dispose();
}
}
private static class AppFrame extends BaseFrame {
JLabel status;
AppFrameWorkListener listener;
public AppFrame(AppFrameWorkListener listener) {
setLocation(200, 200);
status = new JLabel("App Frame");
getContentPane().add(status);
this.listener = listener;
// None of this 'heavy lifting' should be in a constructor.
if (useThread) {
new Thread(new Runnable() {
#Override
public void run() {
doLotsOfWork(4);
}
}).start();
} else {
doLotsOfWork(4);
onWorkDone();
}
}
private void doLotsOfWork(int workLengthSeconds) {
// We're starting. Ensure onWorkStart is called on the EDT,
// as this method may be called from a different Thread.
invokeOnWorkStartOnEDT();
long start = System.currentTimeMillis();
// Hammer the CPU for "workLengthSeconds" number of seconds.
// And do some contrived progress reporting.
long workLengthMs = workLengthSeconds * 1000;
while (System.currentTimeMillis() - start < workLengthMs) {
long innerStart = System.currentTimeMillis();
// Consume 250ms CPU before issuing progress update.
while (System.currentTimeMillis() - innerStart < 250);
invokeOnWorkProgressOnEDT(System.currentTimeMillis() - start);
}
// We're done now. Ensure onWorkDone is called on the EDT,
// as this method may be called from a different Thread.
invokeOnWorkDoneOnEDT();
}
private void invokeOnWorkStartOnEDT() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
onWorkStart();
}
});
}
private void invokeOnWorkProgressOnEDT(final long timeElapsed) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
onWorkProgress(timeElapsed);
}
});
}
private void invokeOnWorkDoneOnEDT() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
onWorkDone();
}
});
}
private void onWorkStart() {
status.setText("Work Started");
if (null != listener) {
// Tell someone who's interested in the work status.
listener.appFrameWorkStart();
}
}
private void onWorkProgress(long timeElapsed) {
status.setText("Work has taken " + timeElapsed + "ms so far");
if (null != listener) {
// Tell someone who's interested in the work status.
listener.appFrameWorkProgress(timeElapsed);
}
}
private void onWorkDone() {
status.setText("Work Done");
if (null != listener) {
// Tell someone who's interested in the work status.
listener.appFrameWorkDone();
}
}
}
interface AppFrameWorkListener {
public void appFrameWorkDone();
public void appFrameWorkStart();
public void appFrameWorkProgress(long timeElapsed);
}
}
You Should use Java Thread and you can show an interactive Splash Screen (Custom made) to your user in the mean while while your code is generating whatever you want here is a tutorial just take a look
You should use Threads for good and efficient concurrency thats it