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);
Related
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...
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.
I have called a method in ServletContextListener as thread ..Now as per my need i have to delay the thread for 1 minutes and then start executing the method called in the thread but i am not able to do that as i am very new in this...
Here is my code ...
public class Startup implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent sce) {
}
public void contextInitialized(ServletContextEvent sce) {
// Do your startup work here
System.out.println("Started....");
//captureCDRProcess();
new Thread(new Runnable() {
#Override
public void run() {
captureCDRProcess();
}
}).start();
}
Please help me ..
Thanks in advance..
To do this properly, you need to use a ScheduledThreadPoolExecutor and use the function schedule like this:
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);
executor.schedule(new Runnable() {
#Override
public void run() {
captureCDRProcess();
}
}, 1, TimeUnit.MINUTES);
Thread.sleep is not the way to go, because it does not guarantee that it wakes up after a minute. Depending on the OS and the background tasks, it could be 60 seconds, 62 seconds or 3 hours, while the scheduler above actually uses the correct OS implementation for scheduling and is therefore much more accurate.
In addition this scheduler allows several other flexible ways to schedule tasks like at a fixed rate or fixed delay.
Edit: Same solution using the new Java8 Lamda syntax:
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);
executor.schedule(() -> captureCDRProcess(), 1, TimeUnit.MINUTES);
Or you can delay creating the thread with Timer and TimerTask:
public void contextInitialized() {
// Do your startup work here
System.out.println("Started....");
Timer timer = new Timer();
TimerTask delayedThreadStartTask = new TimerTask() {
#Override
public void run() {
//captureCDRProcess();
//moved to TimerTask
new Thread(new Runnable() {
#Override
public void run() {
captureCDRProcess();
}
}).start();
}
};
timer.schedule(delayedThreadStartTask, 60 * 1000); //1 minute
}
Have a look at Thread.sleep(). Maybe add it to the new thread's run method, so that it sleeps the needed time before doing any meaningful work.
You can start thread and inside the thread use sleep method for one minute.
ScheduledThreadPoolExecutor has this ability, but it's quite heavyweight.
Here's a simple implementation with a test (signature close to Android's Handler.postDelayed()):
public class JavaUtil {
public static void postDelayed(final Runnable runnable, final long delayMillis) {
final long requested = System.currentTimeMillis();
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
long leftToSleep = requested + delayMillis - System.currentTimeMillis();
if (leftToSleep > 0) {
Thread.sleep(leftToSleep);
}
break;
} catch (InterruptedException ignored) {
}
}
runnable.run();
}
}).start();
}
}
Test:
#Test
public void testRunsOnlyOnce() throws InterruptedException {
long delay = 100;
int num = 0;
final AtomicInteger numAtomic = new AtomicInteger(num);
JavaUtil.postDelayed(new Runnable() {
#Override
public void run() {
numAtomic.incrementAndGet();
}
}, delay);
Assert.assertEquals(num, numAtomic.get());
Thread.sleep(delay + 10);
Assert.assertEquals(num + 1, numAtomic.get());
Thread.sleep(delay * 2);
Assert.assertEquals(num + 1, numAtomic.get());
}
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.
how to stop a timer in java at specific time?
Timer particularTimer = new Timer();
final Timer certainTimer = new Timer();//u can declare a final timer for certain process
particularTimer.schedule(new TimerTask() {
public void run(){
System.out.println("run particularTimer");
certainTimer.schedule(new TimerTask() {
public void run() {
System.out.println("run certainTimer");
}
}, 5000);// it's my start time in milliseconds
}
}, 5000);
//eg
Thread.sleep(6000);
particularTimer.cancel();//when u cancel the particularTimer,and u can cancel the certainTimer too.
certainTimer.cancel();