I want to have a periodically task that should be run every 30 seconds. so I'm using ScheduledThreadPoolExecutor or Timer
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleWithFixedDelay(new MyTask(), 0, 30000, TimeUnit.MILLISECONDS);
class MyTask implements Runnable {
#Override
public void run() {
}
}
Here is Timer
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// do something here
}
}, 0, 30000);
My question is: is there any differences if I start above code inside Service/IntentService or inside one activity. Those actions will be same or start inside service will better.
If you want to run this task even when your app is in backgroud then You should use a service or if you want to run in only when your app is in front so you may use it in activity
Related
I am new to programming and I am doing one android application on which I have one requirement where I need to monitor some logs for the 30s. I am using a timer task but what is happening, if the 30s are over and the run method executed once it is terminated the timer task not repeating.
Here is my code:
connectivityTimerTask = new ConnectivityTimerTask();
timer = new Timer(true);
//timer = new Timer(); // tried with this but it is not working
timer.schedule(connectivityTimerTask,30 * 1000);
TimerTask:
public class ConnectivityTimerTask extends TimerTask {
#Override
public void run() {
Log.error("----- ACK NotReceived -----" + System.currentTimeMillis());
//resetMonitor(); using this method I am setting the timer again
}
}
I want to know what's the best practice for scheduling repeating time.
Am I using the correct way? Can I use the resetMonitor() method?
Instead of of schedule(), You can use Timer task that can be scheduled at fixed rate with scheduleAtFixedRate,
int THIRTY_SECONDS = 30 * 1000;
Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// do whatever you want every 30s
Log.e("TAG", "----- ACK NotReceived -----" + System.currentTimeMillis());
}
}, 0, THIRTY_SECONDS);
Whenever you want to stop the timer call timer.cancel()
The line
timer.schedule(connectivityTimerTask,30 * 1000)
runs your task after a 30s delay and once the task completes, the timer's job is done.
If you want to keep running your task at periodic intervals, you have to also specify an interval period
schedule (TimerTask task, long delay, long period) // "period" specifies how often you want to run the task
Read the documentation here.
To repeatedly run some code after a set period of time, use a Runnable with a Handler like so
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// do your logging
handler.postDelayed(this, 30000);
}
};
handler.post(runnable); // or handler.postDelayed(runnable, 30000) if you want it to wait 30s before starting initially
To cancel
handler.removeCallbacks(runnable);
Is there a way to run a timer task only after the method completes. The method could take 10 seconds but the timer is set to run every 5 seconds. I want it to run again only after the 10 seconds are up.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
longRunningMethod();
timer.schedule(task, 0, 5000);
}
};
timer.schedule(task, 0, 10000);
You can use ScheduledExecutorService which has a scheduleWithFixedDelay() method which does exactly that.
"Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next."
So you could do
ExecutorService.newScheduledExecutor()
.submit(this::longRunningMethod, 0, 1000, ChronoUnit.MILLIS);
Removing the timer.schedule(task, 0, 5000); call will give you behavior you desire.
Your call of timer.schedule(task, 0, 10000); schedules repeating tasks every ten seconds.
You need to schedule one-shot timer tasks and create new TimerTask instance every time.
class MyTimerTask extends TimerTask {
private final Timer timer;
private final long nextScheduleDelay;
MyTimerTask(Timer timer, long nextScheduleDelay) {
this.timer = timer;
this.nextScheduleDelay = nextScheduleDelay;
}
#Override
public void run() {
longRunningMethod();
timer.schedule(new MyTimerTask(timer, nextScheduleDelay), nextScheduleDelay);
}
}
Timer timer = new Timer();
timer.schedule(new MyTimerTask(timer, 1000), 0);
I want to make my listener to run muti-times, this my solution but i guess this will make a problem and number of threads in memory will be very large is it??
Timer timer = new Timer();
executor = Executors.newSingleThreadScheduledExecutor();
timer.schedule(new TimerTask() {
#Override
public void run() {
scheduleTime = Config.NILEDOX_INBOUND_AUTOIMPORT_ROTATE;
if(scheduleTime>=1){
/** setup single thread to run background service every x minutes **/
service = new AutoInboundMailImportService();
executor.scheduleWithFixedDelay(service,1,1,TimeUnit.MINUTES);
}
}}, 120000, 60000);
any idea??
Hi I am working on TCP socket.
I can read data for every 1 sec. to achieve it I used TimerTask as shown in below code.
Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
finalizer = new Runnable() {
public void run() {
try {
if (navBool) {
runOnUiThread(new Runnable() {
public void run() {
new RetriveStock().execute(); // AsyncTask.
}
});
}
} catch (Exception e) {
}
}
};
handler.post(finalizer);
}
};
timer.schedule(doAsynchronousTask, 0, 1000);
For canceling this timer I used code as
timer.cancel();
timer = null;
handler.removeCallbacks(finalizer);
But it is not cancelling the timer. I do not know why.
Instead of calling timer.cancel(), you should be canceling the task that is assigned to that timer (doAsynchronousTask in your case). Since multiple TimerTasks can be assigned to one timer, calling timer.cancel() will not interfere with a currently running task.
From the Timer JavaDoc:
public void cancel()
Terminates this timer, discarding any currently scheduled tasks. Does
not interfere with a currently executing task (if it exists). Once a
timer has been terminated, its execution thread terminates gracefully,
and no more tasks may be scheduled on it.
I have two AsyncTasks doing network operations. I want to call them periodically (like after one min.). How do I do that? I dont think I can do it on the UI thread. Do i need to create a new thread? Is it possible to implemet this without AlarmManager/Service?
Basically I want to exectue these two statements periodically after one min.
new UploadAsyncTask().execute();
new DownloadAsyncTask().execute();
Thank you
Just use a timer.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
new UploadAsyncTask().execute();
new DownloadAsyncTask().execute();
}
});
}
};
timer.schedule(task, 0, 1000); //it executes this every 1000ms