Lets say I have a method called in my android apps
updateArrayList(double data);
How to run the method in 5 seconds and stop after that?
You shuld try Thread.sleep(INT MILLIS); and in try catch block do operation
use the timer class this is the full code
import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
public class ReminderBeep {
Toolkit toolkit;
Timer timer;
public ReminderBeep(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
//timer.cancel(); //Not necessary because we call System.exit
System.exit(0); //Stops the AWT thread (and everything else)
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new ReminderBeep(5);
System.out.println("Task scheduled.");
}
}
this code from http://www.java2s.com/Code/Java/Development-Class/UsejavautilTimertoscheduleatasktoexecuteonce5secondshavepassed.htm
You can try this:
try { //you need the try and catch otherwise you get an error
Thread.sleep(5000); //this is the actual waiting
} catch (InterruptedException e) { //this can just be "Exception" it means that if the thread is told to start again, it wont cause an error.
System.out.println("This code was told to start again.");
//whatever you want to do if the code is told to start again during this.
}
Related
I am trying to create a simple java program that will run indefinitely and output a number every second. I believe my code here should do this; however, it stops after the variable i gets to either 2, 3 or 4. Randomly. Most of the time it hits 3. I do not think that the program stopping is based on i at all, but something i'm overlooking perhaps.
All this program needs to do is spit out the second count using a timer. I feel like my code might be a little over complicated so please let me know if i'm making it too hard.
package testing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class driver {
static int delay = 1000; //milliseconds
private Timer timer;
int i = 0;
public driver(){
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println(i);
i++;
}
};
timer = new Timer(delay, taskPerformer);
timer.setInitialDelay(0);
timer.start();
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new driver();
}
});
}
}
Everything is just right in your program, but one.
Your program starts (from main() obviously), which starts the timer, timer method initiates the process of displaying time/number every second, and after that, the main thread dies! resulting in completion of program execution.
So to avoid this you simply can keep main thread busy.
Here's the simplest way :
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
driver d = new driver();
}
});
for(;;); // <-- **Check this out :D**
}
Here is my example code:
package javaapplication35;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javaapplication35.ProgressBarExample.customProgressBar;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
public class ProgressBarExample {
final static JButton myButton =new JButton("Start");
final static JProgressBar customProgressBar = new JProgressBar();
private static final JPanel myPanel = new JPanel();
public static void main(String[] args) {
customProgressBar.setMaximum(32);
customProgressBar.setStringPainted(true);
myPanel.add(customProgressBar);
myPanel.add(myButton);
myButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
Thread firstly =new Thread(new Runnable (
) {
#Override
public void run() {
Calculations a = new Calculations();
a.doCaculations();
}
});
Thread secondly =new Thread(new Runnable (
) {
#Override
public void run() {
JOptionPane.showMessageDialog(null,"just finished");
}
});
firstly.start();
try {
firstly.join();
} catch (InterruptedException ex) {
Logger.getLogger(ProgressBarExample.class.getName()).log(Level.SEVERE, null, ex);
}
secondly.start();
}
});
JOptionPane.showMessageDialog(null, myPanel, "Progress bar test", JOptionPane.PLAIN_MESSAGE);
}
}
class Calculations {
public void doCaculations() {
new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
int value = 0;
while (value < customProgressBar.getMaximum()) {
Thread.sleep(250);
value ++;
customProgressBar.setValue(value);
}
return null;
}
}.execute();
}
private void doOtherStaff(){
//more methods, that don't need to run in seperate threads, exist
}
}
There are 2 Threads.
The firstly thread creates a Calculations class insance and then runs a doCaculations() method on it.
The secondly thread pops-up a message.
The doCaculations() method in my "real" code performs some time consuming maths and in order to simulate the time spent I added that Thread.sleep(250);. I need to inform the user on the progress of the calculations so I am using the progressbar, that is updated by the doCaculations() method.
I am trying to make the code work in a way that the secondly thread runs after the firstly thread finishes. But I cannot make it work. What happens is that the pop-up message pops-up immediately (and that means that it's thread run before I want it to run).
Note:The "just finished" message is there just to test the code. In my "real" program a method would be in it's place. I am making this note because if I just wanted a message to show I could just place it in the end of the doCaculations() method, and everything would work fine.
I know I must be doing wrong with the Thread handling but I cannot find it. Any ideas?
PS: A thought: Actually the doCaculations() method has its own thread. So it runs "in a SwingWorker inside a Thread". Iguess the firstly.join(); works correctly. But after the doCaculations() method is called the fistrly thread is considered finished, and that's why the code goes on with the secondly thread, not knowing that the doCaculations() thread is still doing something.
In java you can use swingworker and in the done() method call your Dialog
In android you can use AsyncTask for calling the new thread and in the OnPostExecute method, call show message dialog.
Try
a.doCaculations();
a.join();
edit:
Since you are using SwingWorker my previous answer is incorrect, but, as in you comment, you've extended Thread, the following should work for you:
Thread a = new Calculations();
a.start();
a.join();
Don't forget, that you have to override run method in Calculations class, like:
class Calculations extends Thread {
#Override
public void run() {
//your code here
}
}
Your Calculations class must extend SwingWorker. You do your calculations in doInBackground()
public class Calculations extends SwingWorker<Void, Void>{
#Override
protected Void doInBackground() throws Exception {
System.out.println("Calculating.");
Thread.sleep(3000);
return null;
}
}
And in your actionPerformed() you use Calculations like this.
public void actionPerformed(ActionEvent e)
{
//FISRT run method
Calculations a = new Calculations();
a.execute(); // Start calculations
try {
a.get(); // Wait for calculations to finish
} catch (InterruptedException | ExecutionException e1) {
e1.printStackTrace();
}
//THEN inform that just finished
JOptionPane.showMessageDialog(null,"just finished");
}
EDIT: If you have multiple methods that you would like to run in a SwingWorker you can keep your code almost like it is. But only add these lines.
public class Calculations{
protected void calculate() {
SwingWorker sw = new SwingWorker(){
#Override
protected Object doInBackground() throws Exception {
System.out.println("Calculating.");
Thread.sleep(3000);
return null;
}
};
sw.execute(); //Start
try {
sw.get(); //Wait
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
In each method of Calculations you create a new SwingWorker like you did and wait for it to finish by calling SwingWorker.get();
I have an application made in Netbeans and I don't have any idea how to use a Timer in Java. In Winform there's a control box of Timer which is drag and use only. Now I want to use a timer for 1 seconds after about.setIcon(about4); (which is GIF) is executed.
import javax.swing.ImageIcon;
int a2 = 0, a3 = 1, a4 = 2;
ImageIcon about2 = new ImageIcon(getClass().getResource("/2What-is-the-Game.gif"));
about2.getImage().flush();
ImageIcon about3 = new ImageIcon(getClass().getResource("/3How-to-play.gif"));
about3.getImage().flush();
ImageIcon about4 = new ImageIcon(getClass().getResource("/4About-end.gif"));
about4.getImage().flush();
if(a2 == 0)
{
a2=1;
a3=1;
about.setIcon(about2);
}
else if (a3 == 1)
{
a3=0;
a4=1;
about.setIcon(about3);
}
else if (a4 == 1)
{
a4=0;
a2=0;
about.setIcon(about4);
}
}
How can I achieve this?
In Java, we have several ways of Timer implementation or rather its uses, a few of them are-
To set up a specific amount of delay until a task is executed.
To find the time difference between two specific events.
Timer class provides facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
public class JavaReminder {
Timer timer;
public JavaReminder(int seconds) {
timer = new Timer(); //At this line a new Thread will be created
timer.schedule(new RemindTask(), seconds*1000); //delay in milliseconds
}
class RemindTask extends TimerTask {
#Override
public void run() {
System.out.println("ReminderTask is completed by Java timer");
timer.cancel(); //Not necessary because we call System.exit
//System.exit(0); //Stops the AWT thread (and everything else)
}
}
public static void main(String args[]) {
System.out.println("Java timer is about to start");
JavaReminder reminderBeep = new JavaReminder(5);
System.out.println("Remindertask is scheduled with Java timer.");
}
}
Read more from here:
http://javarevisited.blogspot.in/2013/02/what-is-timer-and-timertask-in-java-example-tutorial.html
http://www.javatutorialhub.com/timers-java
Declare an instance of java.util.Timer in your code (in the constructor?) and configure/control it with the methods found in the docs.
import java.util.Timer;
import java.util.TimerTask;
...
private Timer t;
public class MyClass()
{
t=new Timer(new TimerTask(){
#Override
public void run()
{
//Code to run when timer ticks.
}
},1000);//Run in 1000ms
}
Why won't this work?
I would like it to print every second.
Thanks.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class test2 {
public static void main(String[] args) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("hello");
}
});
timer.start();
}
}
Your program terminates before the timer can run even once. When the main method is terminated the program terminates and all threads will also terminate. This includes your timer thread.
Try the following:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class test2 {
public static void main(String[] args) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("hello");
}
});
timer.start();
}
while (true) /* no operation */;
}
}
Probably the timer is started in a daemon thread, and immediately after starting it, the main thread finishes.
As soon as there are only daemon threads left, the JVM may/must terminate. So you need to keep the main thread alive. For testing purposes a simple Thread.sleep(10000); should do well.
There's nothing preventing your code from exiting immediately after the call to start. Add Thread.sleep(10000); after timer.start(); and you'll see the message printed.
Because your program will exit soon after main thread is finished, and since timer runs on a separate thread it won't have time to execute. Adding a Thead.Sleep call before main method end would execute your code.
You are using interface libraries (java.awt) to write console applications.
Try this:
public static void main(String[] args) throws Exception {
while(true){
Thread.sleep(1000);
System.out.println("hello");
}
}
In my java swing application am having a Jframe and Jlabel for displaying current time.
here am using a thread for displaying time in jlablel which is added to the frame.my doubt is that when i dispose the jframe what will happen to the thread whether its running or stopped.
If you have NOT marked your thread as daemon by calling yourThread.setDaemon(true), it will keep running even if main thread in your application has finished. Remember you have to call setDaemon before starting the thread.
Refer my answer to some previous question for details.
The correct way in your case, I believe, would be you maintain a 'stop' flag which is watched by your timer thread. Timer thread should exit on reading this flag as 'false'. You can add a WindowListener to your jframe and on the window closed event set the 'stop' flag to true
Heres example code for what I am suggesting :
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class JFrameTest {
public static void main(String[] args) {
final Timer t = new Timer();
t.start();
JFrame jf = new JFrame("GOPI");
jf.setVisible(true);
jf.setSize(100, 100);
jf.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
t.stopTimer();
}
});
System.out.println("JFrameTest.main() DONE");
}
}
class Timer extends Thread {
boolean stop = false;
#Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (stop)
break;
System.out.println("Counting :" + i);
}
System.out.println("Timer exit");
}
public void stopTimer() {
stop = true;
}
}
Your thread will keep running.
You need to either do as suggested by Gopi or you could use System.exit(0) in close operation of your JFrame.
NOTE: I am assuming here that Your application needs to end if this Frame is closed.