I'm a novice at Java, and I've been trying to use java.util.timer to reset an existing timer after taking the right command input.
However, I've been unable to cancel the timertask properly, so the timer thread runs multiple instances of the timertask if the method is called multiple times. Any help would be appreciated.
Edit: I've changed the location of new Timer(), but it doesn't seem to have fixed it.
Timer timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
public static void main (String[] args) {
Timer timer = new Timer();
while (true) {
//BufferedReader to read input
//Something
if (input[0].equals("r")) {
time t = new time();
time.RestartTimer();
}
}
}
public void RestartTimer() {
ttimer.cancel();
timer.cancel();
Timer timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}
This is happening because you are creating a new instance of time class (time t = new time(); ) inside the while loop. Instead do this :
public static void main (String[] args) {
time t = new time(); // create an instance of time class
while (true) {
//Something
if (input[0].equals("r")) {
// call RestartTimer on the same in
t.RestartTimer();
}
}
}
Also inside RestartTimer() function you are creating new instance of Timer. Change it as follows :
public void RestartTimer() {
ttimer.cancel();
timer.cancel();
timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}
time.RestartTimer(); statement won't be called until and unless either you change the modifier of method or call this method by using static object in main method. I think this is the only reason that your timer is not getting update.
Related
I want Timer execute repeat.
so I try this source
public static void init() {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
Looper.prepare();
recordWork();
Looper.loop();
}
};
Timer timer = new Timer();
timer.schedule(timerTask, 1000, 30000);
}
init() called when record button click.
why recordWork() only one execute?
this timer not execute repeat.
How to fix this problem?
thanks.
Use the function timer.scheduleAtFixedRate() to execute the timer every X seconds.
For example timer.scheduleAtFixedRate(timerTask, new Date(), 2000) to start the timer now and execute every 2 seconds.
Use it like below
public static void init() {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
Looper.prepare();
recordWork();
Looper.loop();
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 1000, 30000);
}
Use Timer as a global variable. and cancel it its need done.
if(timer != null) {
timer.cancel();
timer.purge();
timer = null;
}
If you still can't fix your Timertask. Might as well give CountDownTimer a try
https://developer.android.com/reference/android/os/CountDownTimer.html
public void startCountDown() {
countDownTimer = new CountDownTimer(totalTimeinMillis,intervalBetweenCountdown) {
#Override
public void onTick(long millisUntilFinished) {
//execute repeating task here
}
#Override
public void onFinish() {
}
};
}
Use handler
Handler handler = new Handler();
int delay = 2000; //milliseconds
handler.postDelayed(new Runnable(){
public void run(){
recordWork();
handler.postDelayed(this, delay);
}
}, delay);
Actually i wanted to ask can i give value from database to a timer delay?
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// whatever
}
}
});
}
};
timer.schedule(timerTask,2000,**myDelay**); //here at my delay
Here at myDelay, can i give different values through database? Or it must be fixed?
If you are to change the time all the time with different values, I suggest you use
schedule(TimerTask task, long time)
Everytime you have a new time from DB, just create a new Timer() like so
time = getNewTimeFromDB();
createNewTask(time);
....
private void createNewTask(long time) {
Timer timer=new Timer();
TimerTask timerTask=new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// whatever
}
});
}
};
timer.schedule(timerTask,time);
}
The good thing about this is you don't have to cancel the timer every single time because it is meant to run once.
May you should change your approach to the problem, create a function to return the time from the database FunctionToGetDelayFromDB();
Timer timer=new Timer();
long time = FunctionToGetTimeFromDB();
TimerTask timerTask=new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// whatever
timer.schedule(timerTask, System.currentTimeMillis() + FunctionToGetDelayFromDB());
}
}
});
}
};
timer.schedule(timerTask, System.currentTimeMillis() + FunctionToGetDelayFromDB());
This should work for what you want to achieve...
When i currently call my method
public void flip() {
Image change = new ImageIcon(this.getClass().getResource(imageName[0])).getImage();
ImageIcon card = new ImageIcon(change);
imagelbl.setIcon(card);
}
Currently when the method is called the code runs and the method works. This is perfect however i need there to be a delay of 1 second before the method runs.
I have tried using setTimeout() but i was unsuccessful. How would i get this method to have a 1 sec delay before running?
Use the Timer class for timing.
public void callerMethod() {
System.out.println("Start");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
delayedMethod();
}
}, 1000);
}
public void delayedMethod() {
System.out.println("Test");
}
Use Thread.sleep(1000) as the first line in flip() method.
I want to run a thread (Which does some time consuming task in background and does NOT update UI) it just downloads some files form the internet and it is independent from the UI.
I want to run this thread repeatedly after some time interval.
How can i do this, I have thread something like below:
boolean mResult =false;
void onCreate()
{
DownloadThread mDownloadThread = new DownloadThread();
mDownloadThread.start();
}
class DownloadThread extends Thread implements Runnable
{
public void run()
{
// My download code
mResult = result;
}
}
Do i need to use Handler for implementing this?
Option 1:
volatile boolean flag = true;
public void run()
{
while(flag)
{
// Do your task
try{
Thread.Sleep(interval);
} catch(Exception e){
}
}
}
Option 2:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Do your task
}
}, 0, interval);
Option 3:
volatile boolean flag = true;
public void someMethod(){
// Do your task
try{
Thread.Sleep(interval);
} catch(Exception e){
}
if(flag)
return;
else
someMethod();
}
Option 4:
final Handler handler = new Handler();
volatile boolean flag = true;
Class A implements Runnable{
public void run(){
// Do your Task
}
if(!flag)
handler.postDelayed(a, interval);
}
A a = new A();
handler.postDelayed(a);
There will be many more options. I never tried option 3 and 4. It just came to my mind and I wrote. If I were you I would use any of 1 or 2.
Prefered choice is
java.util.concurrent.ScheduledExecutorService
Newer and robust implementation, More here ScheduledExecutorService
I would use a Timer to achieve this. Try this:
void onCreate()
{
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Download your stuff
}
}, 0, 1000);
}
It starts immediately and the run-Method gets called every second.
Hi m using the following timer task,and i want to increase the time of this task when a certain condition occurs
Timer timer2=new Timer();
timer2.schedule(new TimerTask(){
public void run(){
//whatevr
}
}, 4000);
examlpe
if(mycondition)
{
increase time????
}
how can i do that
Extract the TimerTask in an inner or standalone class. Cancel currently running timer task and schedule a new instance with increased time period.
You can't. You'll have to schedule a new task with the incremented period. And if the previous task has become obsolete, make sure that you cancel() it.
For future reference, I recommend you utilize the Executors framework.
Submit another one task from run() if necessary:
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTaskTest {
private static class MyTimerTask extends TimerTask {
private final Timer timer;
private boolean fire;
private MyTimerTask(Timer timer) {
this(timer, false);
}
private MyTimerTask(Timer timer, boolean fire) {
this.timer = timer;
this.fire = fire;
}
#Override
public void run() {
if (!fire) {
System.out.println(new Date() + " - steady...");
timer.schedule(new MyTimerTask(timer, true), 2000);
} else {
System.out.println(new Date() + " - go!");
}
}
}
public static void main(String args[]) {
Timer timer = new Timer(true);
MyTimerTask timerTask = new MyTimerTask(timer);
System.out.println(new Date() + " - ready...");
timer.schedule(timerTask, 4000);
try {
Thread.sleep(7000);
} catch (Exception ignore) {
}
}
}