Java execute method from within a loop every few seconds - java

I have a Thread that runs in my test app with a while loop inside the thread. While the while loop is running i want to execute a method from within this while loop every 30 seconds. Inside the while loop, don't want to sleep the thread or stop the loop, it must run and every 30 seconds call the method.
Thread myThread = new Thread() {
#Override
public void run() {
//my code that runs with a loop
//while loop here that runs and needs to execute method every 30 seconds, if condition met continue else break;
};
myThread.start();
}

To wait, you can use
Thread.sleep(milliseconds);
For documentation, see here
If you wait for 30 seconds in your loop, it happens every 30 seconds + execution time of your function. As long as your function call only takes milliseconds this is as precise as doing it in a more complex way.
If you want your loop to keep running but you do not want to launch a new Thread, you can use the current Time:
long lastCall = 0;
while(bla) {
if(System.currentTimeMillis() - lastCall > 30000) {
lastCall = System.currentTimeMillis();
callTheFunction();
}
}

Place it where thread is executed:
Thread.sleep(30000);

Related

Accurate thread loop. Run a task with precise interval

I want my thread to perform an action 4 or 16 times per bpm (beats per minute). This timer is not 100% accurate, after a few seconds it desynchronizes from the metronome I found on youtube, and it gets a little slower than it should.
bpm = (float) my music bpm;
thread = new Thread(()->{
long now ;
long total ;
while (true) {
long bpmTime = (long) ((1000000000*60d)/(bpm*16));
now = System.nanoTime();
bpmTick(); //<-- my task
try {
total = System.nanoTime() - now;
if(total > bpmTime) {
continue;
}
Thread.sleep((bpmTime - (System.nanoTime() - now)) / 1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
I also tried:
Thread.sleep((long)(1000*(60.0/bpm)));
but the same problem occurs
In short, I need a metronome.
Thanks in advance.
What you want to use is a ScheduledExecutorService instance instead. This class can repeat the task in a Thread repeatedly at a fixed rate. The class has a method called scheduleAtFixedRate(task, intialDelay, DelayBetweenExecutions,TimeUnit) just for this purpose.
When the initial delay is set to 0 the task will run as soon as scheduleAtFixedRate is called and will continue doing so until you call shutdown() or shutdownNow() on the service. Here's an example that uses some of your code:
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
int timesPerBPM = 16;
long bpmTime = 900; //or whatever the outcome of your formula is.
Thread thread = new Thread(()->{
for (int i = 0; i < timesPerBPM; i++) //do task 16 times
bpmTick(); //<-- my task
});
executorService.scheduleAtFixedRate(thread, 0, bpmTime, TimeUnit.MILLISECONDS); //This will start immediately because initialDelay is 0.
executorService.shutdown(); //Always shutdown service when done to avoid memory leaks.
The executorService in the below code will run bpmTick() 16 times every 900 milliseconds. If it takes longer then 900 milliseconds to run bpmTick() 16 times the service will wait for the current task to complete until it starts the next repetition. So to keep things synchronized the 16 bpmTick() must always finish within bpmTime milliseconds. If you want to guarantee a 150 millisecond pause between threadtask executions regardless of how long it takes to execute a task then you should use the method scheduleWithFixedDelay() instead.
If you want the service to repeat the task every minute instead of every 900 milliseconds then it is best to change bpmTime to 1 and TimeUnit.MILLISECONDS to TimeUnit.MINUTES.

How to run code inside for loop every 5 seconds in java? [duplicate]

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);

Android Java - Runnable confusion

I'm learning about Runnable right now and am a little confused with a code I found and how it's running.
j = 0;
public Runnable test = new Runnable() {
#Override
public void run() {
if (j <= 4) { //this is an if statement. shouldn't it run only once?
Log.i("this is j", "j: " + j);
handler.postDelayed(this, 2000); //delays for 2 secs before moving on
}
j++; //increase j. but then why does this loop back to the top?
Log.i("this is j", "incremented j: " + j);
}
};
When I run this, every 2 seconds j will log from 0 to 4. I don't understand why though, but it does exactly what I need of having a data updated every 2 seconds.
Does run() just keep... running? Which would explain why it keeps looping, kinda. But then if that was the case then even after the if statement finishes j would still be incrementing itself.
Any help in explaining this would help, thanks!
Check out the documentation for Handler.postDelayed(Runnable, long):
Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses.
What postDelayed() does is take a Runnable instance and call its run() method after a given delay. It does not resume execution where you left off.
In your case, you are passing this which is a Runnable that checks if (j <=4 )) and if so, posts that same runnable again, thus executing the run() method again.
If you just want a delay after checking if j <= 4, you likely want Thread.sleep() which will sleep a thread for a given amount of time.
A Runnable is just that: a block of code that can be run. The magic happens when you use Runnable's with a Handler, like you are doing here. A Handler will accept Runnable's and call their run() method on the Handler's thread. You tell a Handler to run a Runnable using Hander.post() or Handler.postDelayed(). post() runs the Runnable immediately, postDelayed() runs it after a given amount of milliseconds.
So the run() method is only run once, but this line:
handler.postDelayed(this, 2000);
tells the Handler to schedule running this (that is, this Runnable) after 2000 milliseconds (2 seconds).

kill process after some time in java

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

Load Test using Java - timer task vs scheduler

I need to execute a load test using Java in which one of the test strategies require x threads to be fired of every y period of time for z minutes and thereafter have a constant totalThread amount of threads running for the load test duration (eg with a total of 100 threads, start 10 threads at 5 second intervals until all 100 threads have started, and continue to keep all 100 threading running (once it has finished execution it should restart) for the specified duration of the test, say one hour)
I have attempted to use the timer task but it seems limiting, would thread pool scheduler be a better option? What would be the best approach?
public class MyTask extends TimerTask{
public void run() {
System.out.println("STARTING THREAD "+ counter +" "+ new Date());
//execute test
counter++;
if (counter > maxIterations) {
MyTask.this.cancel();
return;
}
}
List<TimerTask> MyTaskList = new ArrayList<TimerTask>();
for (int i = 1 ; i <= threadsPerIteration ; i++) {
TimerTask MyTimerTask = new MyTask(NumberOfIterations);
MyTaskList.add(MyTimerTask);
timer.schedule(MyTimerTask, initialDelayMilli, threadDelayMilli);
}
Thank You
Don't use a TimerTask for each thread. Instead, use a single TimerTask, that fires once per interval, with your example numbers once every 5 seconds.
Each of the first 10 times the TimerTask fires, it spawns off 10 threads. On each subsequent firing, it checks for the number of active threads, and spawns off enough new threads to bring the total to 100, until the end of your test.
Thanks for the help, i decided to use the threadpool executor together with the timertask class as follows:
I used the Executors.newScheduledThreadPool(int x) method to control the amount of threads able to run concurrently, together with a timer task that is set to increase the threadpool size every y amount of time :
TimerTask DelayTimerTask = new TimerTask() { //task to increase threadpool size
public void run() {
MyExecutor.setCorePoolSize(i * incrementAmount); //timer task increments threadpool size by threadPoolIncrement
i++;
}
};
timer.scheduleAtFixedRate(DelayTimerTask,0,intervalLength);
in this way the amount of concurrent threads will increase by incrementAmount every intervalLength.

Categories

Resources