Timer in java with Threads - java

I want to print this line:
System.out.println(Runtime.getRuntime().freeMemory());
every second. How to do it?
public class Hilo implements Runnable{
Thread t;
String nombre;
public Hilo() {
t = new Thread(this,"Hilo1");
t.start();
}
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}

Use a java.util.Timer object.
A 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.
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}, 0, 1000);

Another way to do it
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}, 0, 1, TimeUnit.SECONDS);
ses.shutdown();
Differences between java.util.timer and ScheduledExecutorService
ScheduledThreadPoolExecutor are not sensitive to changes in the system clock but Timer is.
Timer has only one execution thread, so long-running task can delay other tasks.
ScheduledThreadPoolExecutor can be configured with any number of threads

By using below code you can print that want after every second
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}, 0, 1000);
}

Related

Java TimerTask in While Loop [duplicate]

I am using java.util.Timer class and I am using its schedule method to perform some task, but after executing it for 6 times I have to stop its task.
How should I do that?
Keep a reference to the timer somewhere, and use:
timer.cancel();
timer.purge();
to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.
private static int count = 0;
public static void run() {
count++;
if (count >= 6) {
timer.cancel();
timer.purge();
return;
}
... perform task here ....
}
Either call cancel() on the Timer if that's all it's doing, or cancel() on the TimerTask if the timer itself has other tasks which you wish to continue.
You should stop the task that you have scheduled on the timer:
Your timer:
Timer t = new Timer();
TimerTask tt = new TimerTask() {
#Override
public void run() {
//do something
};
};
t.schedule(tt,1000,1000);
In order to stop:
tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread
Notice that just cancelling the timer will not terminate ongoing timertasks.
Terminate the Timer once after awake at a specific time in milliseconds.
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);

Paho-Mqtt Periodic Publications approaches

What is the best way to publish safely data periodically ?
First approach:
while(true){
Thread.sleep(1000);
//pub
}
second:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//pub
}
}
third:
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
ses.scheduleAtFixedRate(new Runnable() {
public void run() { //pub }
}, 0, 3, TimeUnit.SECONDS);

Threads running at specific time intervals for a specific time in JAVA

I want to use the below mentioned operations in JAVA for android development.
For 30 Seconds ,Run a Function F1() every 1 second (resulting in 30 F1 calls).
Run a Thread t1 forever
The above steps should execute sequentially.
I Have tried with ExecutorServicebut with no success.
This is my code for reference
final Handler h = new Handler();
final int delay = 1000; //milliseconds
ExecutorService executor = Executors.newFixedThreadPool(1);
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
F1();
}
});
for(int i=0;i<30;i++){
executor.submit(t1);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
executor.shutdown();
//Step 2 (THe Second Thread)
h.postDelayed(new Runnable() {
public void run() {
AnotherFunction()
h.postDelayed(this, delay);
}
}, delay);
Generally, ExecutorService is more preferable for such operations. Here is a good post describing the differences and features of Timer and ExecutorService.
As for your question directly - it can be implemented in such way:
// here are Runnables with test logic
Runnable foo = new Runnable() {
#Override
public void run() {
Log.d(">>>", "foo");
onTaskFinished();
}
};
Runnable longRunning = new Runnable() {
#Override
public void run() {
try {
Log.d(">>>", "longRunning started");
Thread.sleep(5000);
Log.d(">>>", "longRunning finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// and here is valuable logic
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> schedulerHandler;
volatile AtomicInteger tasksNum = new AtomicInteger(0);
private synchronized void onTaskFinished(){
if(tasksNum.incrementAndGet() >= 30){
scheduler.execute(new Runnable() {
#Override
public void run() {
schedulerHandler.cancel(true);
}
});
scheduler.execute(longRunning);
}
}
And then to start operation just invoke this command:
schedulerHandler = scheduler.scheduleAtFixedRate(foo, 0, 1, TimeUnit.SECONDS);
You may consider using the java.util.Timer and java.util.TimerTask classes
If you're doing what I think you're doing you can do as #erosb hinted, use Timer and TimerTask to schedule method executions at a fixed rate.
The following should work for you.
final int DELAY_BEFORE_START = 0;
final int RATE = 1000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
F1();
}
}, DELAY_BEFORE_START, RATE);

Java Timer Usage

Hi I am using a timer for 2 tasks, which will monitor a set of IP address
public input ()
{
timer.schedule(task, 0, 8);
timer_second.schedule(task_monitor, 0, 5);
}
and I have 2 Timer Task
private final TimerTask task = new TimerTask() {
#Override
public void run() {
}
}
private final TimerTask task2 = new TimerTask() {
#Override
public void run() {
}
}
But as per my code logic, input () can be called more than one time , and if i call second time i get IllegalStateException: Task already scheduled or cancelled
Which seems to be obvious, but my logic is input can be called by different IP's and i have to monitor all such IP's using the 2 Timer Task
How should I avoid This ??
Please Help !!!!!
Thanks in advance

Pausing/stopping and starting/resuming Java TimerTask continuously?

I have one simple question regarding Java TimerTask. How do I pause/resume two TimerTask tasks based on a certain condition? For example I have two timers that run between each other. When a certain condition has been met inside the task of first timer, the first timer stops and starts the second timer, and the same thing happens when a certain condition has been met inside the task of second timer. The class below shows exactly what I mean:
public class TimerTest {
Timer timer1;
Timer timer2;
volatile boolean a = false;
public TimerTest() {
timer1 = new Timer();
timer2 = new Timer();
}
public void runStart() {
timer1.scheduleAtFixedRate(new Task1(), 0, 1000);
}
class Task1 extends TimerTask {
public void run() {
System.out.println("Checking a");
a = SomeClass.getSomeStaticValue();
if (a) {
// Pause/stop timer1, start/resume timer2 for 5 seconds
timer2.schedule(new Task2(), 5000);
}
}
}
class Task2 extends TimerTask{
public void run() {
System.out.println("Checking a");
a = SomeClass.getSomeStaticValue();
if (!a) {
// Pause/stop timer2, back to timer1
timer1.scheduleAtFixedRate(new Task1(), 0, 1000);
}
// Do something...
}
}
public static void main(String args[]) {
TimerTest tt = new TimerTest();
tt.runStart();
}
}
So my question is, how do I pause timer1 while running timer2 and vice versa while timer2 is running? Performance and timing is my main concern as this needs to be implemented inside another running thread. By the way I am trying to implement these concurrent timers on Android.
Thanks for your help!
From TimerTask.cancel():
Note that calling this method from
within the run method of a repeating
timer task absolutely guarantees that
the timer task will not run again.
So once cancelled, it won't ever run again. You'd be better off instead using the more modern ScheduledExecutorService (from Java 5+).
Edit: The basic construct is:
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(runnable, 0, 1000, TimeUnit.MILLISECONDS);
but looking into it there's no way of cancelling that task once its started without shutting down the service, which is a bit odd.
TimerTask might be easier in this case but you'll need to create a new instance when you start one up. It can't be reused.
Alternatively you could encapsulate each task as a separate transient service:
final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
Runnable task1 = new Runnable() {
public void run() {
a++;
if (a == 3) {
exec.shutdown();
exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(task2, 0, 1000, TimeUnit.MILLISECONDS)
}
}
};
exec.scheduleAtFixedRate(task1, 0, 1000, TimeUnit.MILLISECONDS);
easiest solution i found: just add a boolean in the run code in the timer task, like so:
timer.schedule( new TimerTask() {
public void run() {
if(!paused){
//do your thing
}
}
}, 0, 1000 );
If you have already canceled one timer, you can't re-start it, you'll have to create a new one.
See this answer, it contains a video and the source code how I did something similar.
Basically there are two method: pause and resume
In pause:
public void pause() {
this.timer.cancel();
}
In resume:
public void resume() {
this.timer = new Timer();
this.timer.schedule( aTask, 0, 1000 );
}
That makes the perception of pause/resume.
If your timers perform different actions based on the state of the application you may consider use the StatePattern
Fist define a abstract state:
abstract class TaskState {
public void run();
public TaskState next();
}
And provide as many states as you like. The key is that one state leads you to another.
class InitialState extends TaskState {
public void run() {
System.out.println( "starting...");
}
public TaskState next() {
return new FinalState();
}
}
class FinalState extends TaskState {
public void run() {
System.out.println("Finishing...");
}
public TaskState next(){
return new InitialState();
}
}
And then you change the state in your timer.
Timer timer = new Timer();
TaskState state = new InitialState();
timer.schedule( new TimerTask() {
public void run() {
this.state.run();
if( shouldChangeState() ) {
this.state = this.state.next();
}
}
}, 0, 1000 );
Finally, if what you need is to perform the same thing, but at different rates, you may consider using the TimingFramework. It is a bit more complex but let's you do cool animations, by allowing the painting of certain component take place at different rates ( instead of being linear )
In my opinion, this is somewhat misguided. If your code needs time guarantees, you can't use Timer anyway, nor would you want to. "This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method."
The answer, IMHO, is that you don't want to pause and restart your timers. You just want to suppress their run methods from doing their business. And that's easy: you just wrap them in an if statement. The switch is on, they run, the switch is off, they miss that cycle.
Edit: The question has shifted substantially from what it was originally, but I'll leave this answer in case it helps anyone. My point is: if you don't care when your event fires in the N millisecond span (just that it doesn't EXCEED once every N milliseconds), you can just use conditionals on the run methods. This is, in fact, a very common case, especially when N is less than 1 second.
Reviewing your source code, here are the changes ( which pretty much validate my previous answer )
In task1:
// Stop timer1 and start timer2
timer1.cancel();
timer2 = new Timer(); // <-- just insert this line
timer2.scheduleAtFixedRate(new Task2(), 0, 1000);
and in task2:
// Stop timer2 and start timer1
timer2.cancel();
timer1 = new Timer(); // <-- just insert this other
timer1.scheduleAtFixedRate(new Task1(), 0, 1000);
It runs on my machine:
Android won't reuse a TimerTask that has already been scheduled once. So it's necessary to reinstantiate both the Timer and TimerTask, for example like this in a Fragment:
private Timer timer;
private TimerTask timerTask;
public void onResume ()
{
super.onResume();
timer = new Timer();
timerTask = new MyTimerTask();
timer.schedule(timerTask, 0, 1000);
}
public void onPause ()
{
super.onPause();
timer.cancel(); // Renders Timer unusable for further schedule() calls.
}
I am able to stop a timer and a task using following code:
if(null != timer)
{
timer.cancel();
Log.i(LOG_TAG,"Number of cancelled tasks purged: " + timer.purge());
timer = null;
}
if(task != null)
{
Log.i(LOG_TAG,"Tracking cancellation status: " + task.cancel());
task = null;
}
Timer timer1;
private boolean videoCompleteCDR=false;
private boolean isVideoPlaying=false;
int videoTime=0;
private int DEFAULT_VIDEO_PLAY_TIME = 30;
#Override
public View onCreate(){
isVideoPlaying = true; //when server response is successfully
}
#Override
public void onPause() {
super.onPause();
if(isVideoPlaying ) {
if(this.timer1 !=null) {
this.timer1.cancel();
}
}
}
#Override
public void onResume() {
super.onResume();
if(isVideoPlaying && !videoCompleteCDR) {
callTimerTask();
}
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (!hidden) {
printLog( "GameFragment visible ");
if(isVideoPlaying && !videoCompleteCDR) {
callTimerTask();
}
} else {
printLog("GameFragment in visible ");
if(isVideoPlaying) {
if(this.timer1 !=null) {
this.timer1.cancel();
}
}
}
}
private void callTimerTask() {
// TODO Timer for auto sliding
printLog( "callTimerTask Start" );
timer1 = new Timer();
timer1.schedule(new TimerTask() {
#Override
public void run() {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (getActivity() == null) {
return;
}
videoTime++;
if(DEFAULT_VIDEO_PLAY_TIME ==videoTime){
videoCompleteCDR=true;
Log.e("KeshavTimer", "callTimerTask videoCompleteCDR called.... " +videoTime);
destroyTimer();
}
Log.e("KeshavTimer", "callTimerTask videoTime " +videoTime);
}
});
} else {
printLog("callTimerTask getActivity is null ");
}
}
}, 1000, 1000);
// TODO 300, 2000;
}
private void destroyTimer(){
this.timer1.cancel();
}

Categories