This question already has answers here:
How to exit a while loop after a certain time?
(5 answers)
Closed 6 years ago.
I'm trying to do a script with PowerShell and I need to execute some Java code in a loop. So I do :
while(something){
java my_program
}
But my_program takes time and I would like to set a Timeout. How can I do this?
You could try something like this:
while($something){
$p = [diagnostics.process]::start("java my_program")
if ( ! $p.WaitForExit(1000) )
{
$p.kill()
}
}
I think this code will work fine for you, you can put while loop condition,
public class JavaTimeout {
public void myMethod(){
long startTime = System.currentTimeMillis(); // put the start time
while((System.currentTimeMillis() - startTime ) < 5000) // if if 5 second end
{
// your method do something here
}
System.out.println("5 sec end..."); // print the timeout
} // end myMethod method
} // end JavaTimeout Class
I hope that helps..
Related
This question already has answers here:
How to schedule a periodic task in Java?
(13 answers)
Closed 2 years ago.
how to call method multiple times within given time java
Ex: if I want to call method A() for 3 times within 120 seconds. these two values should be configurable
You should take a look at Timers in Java. Documentation of Java SE 8 of Timer can be found here.
Here's an example: You can adjust the delay, period to your own preference.
// Initialize the Timer, this is the actual function that will start a TimerTask
private static final Timer timer = new Timer();
// Initialize the TimerTask, this is like the recipe for the Timer
private static final TimerTask task = new TimerTask() {
// Create a variable to keep track how many times we have ran this code
private int count = 0;
// Function that will be ran in the TaskTimer
public void run() {
// Your Code goes here
// Add to the amount of times we have ran this code
count++;
// If the count has reached 3...
if( count == 3 ) {
// we cancel the task
task.cancel();
}
}
};
// Using the TimerTask
public static void main( String[] args ) {
// Set the delay (adjust this to your own needs)
long delay = 2000;
// Set the period (adjust this to your own needs)
long period = 5000;
// Schedule the TimerTask
timer.schedule(task, delay, period);
}
It's always a good idea to take a look if your dependency has it's own set of Timer and AsyncTimer, as sometimes it's more efficient to use there's.
This question already has answers here:
Java execute method from within a loop every few seconds
(2 answers)
Closed 2 years ago.
I want to execute specific code located inside for loop every 5 seconds.
How can I do that?
In that case, a java.util.Timer would be a more fitting solution.
A timer allows you to execute a function every x milliseconds.
Though, you'll have to define and call the timer outside of the loop.
Alternatively, you can check out the link that #Filburt has suggested to see in which you can use the current time to execute a code within a loop every x seconds.
If you still want to go with the timer solution, here's how you set it:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run () {
// code to execute
}
}, MILLISECONDS); // replace MILLISECONDS with the amount of milliseconds between each execution.
Note that the timer itself doesn't know when to stop. You can create a field in the anonymous class that counts each execution and cancels the timer when reaching a specific number:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
int times = 0;
#Override
public void run () {
if (times == 5) { // replace 5 with the amount of times you want the code executed.
timer.cancel();
return;
}
// code to execute
times++;
}
}, MILLISECONDS);
i want to terminate some process after some time if that process will not responded
i used this code but i am not able to achive the same
long start = System.currentTimeMillis(); long end = start +60000;
1 while (System.currentTimeMillis() < end)
2 {
3 Connection.execute(function); // execute
4 break; // break if response came
5 }
6 if(System.currentTimeMillis() > end)
7 {
8 close connection; // close connection if line no 3 will not responded
9 }
kindly help me on the same
As the call Connection.execute() is blocking, so main thread will be blocked until it executes, SO in that case if we want to close the connection when the main thread is blocked , we have to close connection in some other thread. May be we can use Timer & TimerTask in this case. I tried to write some code as below, May be you can some thing like that.
Timer timer = new Timer();
while (System.currentTimeMillis() < end) { //In any case, this loop runs for only one time, then we can replace it with IF condition
CloseConnectionTask task = new CloseConnectionTask(Connection);
timer.schedule(task, end); // Task will be excuted after the delay by "end" milliseconds
Connection.execute(function); // execute
task.cancel(); //If the excute() call returns within time ie. "end" milliseconds, then timerTask will not get executed.
break; // break if response came//
}
timer.cancel(); // If you have no more scheduling tasks, then timer thread should be stopped.
Below is TimerTask implementation:
class CloseConnectionTask extends TimerTask {
private Connection con;
public CloseConnectionTask(Connection con) {
this.con = con;
}
#Override
public void run() {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Note: I have one more thing to say, In your while loop, If the call to Connection.execute() successful, then you break from the loop. So what I have observed, In any case your loop is executing only once, If this is the case, then you should use IF(again its what I have seen in the provided code, you requirement may be different). Hope it may help you. If you have other thoughts on this, please share. My answer is based on this link, Good info. is there.
this way it will not help
i think you should implement thread to achieve that
Complete code: https://github.com/Sheldor5/JavaGPP (see tests for both options)
I have some weird behaviors with command patterns and loops (counting down until the actual command action should be executed):
What I am trying to achieve:
I am currently developing a game and in this game I want to place a "bomb" and this "bomb" should explode in e.g. 2 seconds. I am doing this with command patterns where one type of command substracts thedelta from the left timeLeft variable until the timeLeft variable is <= zero --> so if the 2 seconds have passed the explosion should take place. This is not working if I execute the command in a while loop because the bomb explodes after +2.2 seconds and not after 2 (and some nanos). If I add a Thread.sleep(1) in the loop the time is accurate enough for me so I can say the calculation of the delta is done rigth.
Option 1:
// infinite loop: execute all commmands in the executor (only one command for now)
while (true) {
commandExecutor.executeCommands();
}
// the only one command in the executor gets called everytime
public static final long NANOS = 1000000000;
private long timeLeft = NANOS;
private long start;
public Command() {
this.start = System.nanoTime();
}
public execute(final long delta) {
this.timeLeft -= delta;
if (this.timeLeft <= 0) {
final long time = System.nanoTime() - this.start;
System.out.println(String.format("Successfully executed Command with ID '%s' in %dns (%dns)", this.getID(), time, this.timeLeft));
this.timeLeft += NANOS;
}
}
Expected Output (1 second interval):
Successfully executed Command with ID '1' in 1000000454ns (-454ns)
Successfully executed Command with ID '1' in 1000000695ns (-695ns)
Successfully executed Command with ID '1' in 1000000549ns (-549ns)
Successfully executed Command with ID '1' in 1000000003ns (-3ns)
Actual Output ():
Successfully executed Command with ID '1' in 1267062727ns (-266ns)
Successfully executed Command with ID '1' in 1350811695ns (-165ns)
Successfully executed Command with ID '1' in 1352353549ns (-145ns)
Successfully executed Command with ID '1' in 1263098003ns (-75ns)
But if I add a Thread.sleep() into the loop the actual output is much more accurate:
Option 2:
while (true) {
commandExecutor.executeCommands();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Acceptable Output:
Successfully executed Command4 with ID '40' in 1000015964ns (-47338ns)
Successfully executed Command4 with ID '40' in 1001095472ns (-316309ns)
Successfully executed Command4 with ID '40' in 1000039457ns (-224116ns)
Successfully executed Command4 with ID '40' in 1001043666ns (-662982ns)
Can someone explain this to me? Is the loop too fast? Is something so fast that it can't recognize the actual value of the variable and it wrongly sees it as greater than zero? Why there are so big differences and from where are those ~0.2 seconds?
Originally I thought this was a concurrency issue but I don't think it is because your custom executors and commands don't spawn any new threads. Instead I think that youre just instrumenting your time too much. Your code is basically just looping and calling System.nanotime(). The problem with the approach of using your delta variable is that you aren't taking into account the time involved in calling System.nantime (). But youre calling it a lot. I think that using a timer task would be be preferable but if you want to do this yourself try something like the following:
long start = System.nanotime ();
long inTwoSecs = start + 2000000000L;
while (true) {
long now = System.nanotime ();
if (now >= inTwoSecs) {
return;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I was digging around in some old java projects that I never finished and I pulled out this little number that is of my best projects ever built.
It's a desktop clock widget coded in java and it works perfectly fine except for one thing. The way I have it check the current time to stay updated is in a loop and the loop "crashes" in a matter of seconds so the widget no longer gets the current time.
This is how the loop is constructed (reduced in size):
public class getCurrentTime {
public static void getTime() throws InterruptedException {
int hour = global.calendar.get(Calendar.HOUR);
int minute = global.calendar2.get(Calendar.MINUTE);
if(hour == 0) {
global.hour.setIcon(new ImageIcon("resources/hours/12.png"));
}else if(hour == 23) {
global.hour.setIcon(new ImageIcon("resources/hours/11.png"));
}else {
global.hour.setText("?");
}
if(minute == 0) {
global.minute.setIcon(new ImageIcon("resources/minutes/00.png"));
}else if(minute == 59) {
global.minute.setIcon(new ImageIcon("resources/minutes/59.png"));
}else {
global.minute.setText("?");
}
Thread.sleep(1000);
getTime();
}
}
global is a class where I keep most of my variables (I know it's weird, this was like 3 years ago, it's how I used to write my programs).
So my main question is, is there a way that I can prevent the loop from "crashing"?
Thanks in advance!
This is not a loop, really. It is a recursive call. In each recursion, some more memory will be allocated, so it will after some time go out of memory. I wonder why this is a matter of seconds here, but anyway.
Try using a Timer to schedule the gui update.
Edit : you are creating a new ImageIcon in each recursion. They can be rather large in memory. Maybe they are the reason for the rapid "crash".
Apart from that I suggest sticking to java naming conventions. Class names should start with a capital letter.
Thread.sleep(1000); is not going to be a good option. You can use Timer. By using a Timer you schedule a task at regular intervals.
Timer timer = new Timer();
long interval = (1000) ; // 1 sec
timer.schedule( new TimerTask() {
public void run() {
//do your work;
}
}, 0, interval);
If you want to stop the scheduling, you can use timer.cancel();
EDIT: as Fildor said I think memory is your problem. Use timer this way, it should solve your problem.
This is first solution
class clockUpdater implements Runnable {
#Override
public void run() {
Thread.sleep(WAIT_TILL_NEW_MINUTE);
while(true){ //a infinite loop
// the Swing call below must be queued onto the Swing event thread
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
//your clock updating code here
}
});
try {
Thread.sleep(1000*60);//you only need to update once after a minute
} catch (InterruptedException e) {
// ....
}
}
}
}
This is second
class clockUpdater extends Thread{
#Override
public void run(){
Thread.sleep(WAIT_TILL_NEW_MINUTE);
while(true){
try{
//your update code here
Thread.sleep(60*1000)//
}
catch(Exception e){
//..
}
}
}
}
Note: You need to start this as soon as the minute changes in system time. Or clock time will lag behind. Calculate WAIT_TILL_NEW_MINUTE as soon as your program starts. Better to update only when it is needed.
The answer for your question is
use set timeout function for the function
which you want to avoid loop crashing.
Like:
setTimeout(function() {
// write the logic
},1000);