i am developing an app but i need run a function x minutes, i've tried using
scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new Runnable() {
#Override public void run() {
Toast.makeText(ser, "Servicio MyService update", Toast.LENGTH_LONG).show();
}
},
0,
100,
TimeUnit.MILLISECONDS );
}
but it does not work.
i use this function on a service, when the service is running it does'not call the function.
if I understand wrong please correct me,
you can use recursive func,
public void myfunc()
{
new CountDownTimer(70000, 1000) {
public void onTick(long millisUntilFinished) {
//
}
public void onFinish() {
Toast.makeText(getApplicationContext(), "7 seconds have passed",
Toast.LENGTH_LONG).show();//you can do here what you want every x(7)time
//you can put condition here to break recursive
myfunc(); //this calls again.
}
}
}
Related
Is there any way to do a wait() function, in my case, in Android Studio?
function example ()
{
while ()
{
//do something
//wait (x seconds) then go back
}
}
You may achieve this way:
//in your method, use the Timer Schedule function:
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
//TODO: do something here of your interest.
}
},
2000
);
Here I have kept the delay for 2 seconds (2000 milliseconds). You may change that according to your need.
int interval = 3000;//milliseconds interval for delay
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
private void finish() {
// TODO Auto-generated method stub
}
}, interval);
I am developing an application, In which I am sending the device location to the server for every one min. I am using Handler here to schedule my task. After User click the STOP button, the handler should stop its execution. I am unable to achieve this. Please find my code below.
public void callSpecficTime() {
timer = new Timer();
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Log.e("TImeOnSchedule", String.valueOf(inTime));
if(inTime==5)
{
new PostDataAsyncTask().execute();
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 60000);
}
StopTask code :
public void stopTask(){
if(doAsynchronousTask!=null){
Log.d("TIMER", "timer canceled");
handler.removeCallbacks(doAsynchronousTask);
// timer.cancel();
doAsynchronousTask.cancel();
}
}
I tried stopService,removeCallbacks but it didn't work. Can anyone provide me solution for this?
UPDATED
public void onClickButton(View v)
{
if(v.getId()==R.id.IBstart)
{
callAsynchronousTask();
callSpecficTime();
}
else if(v.getId()==R.idIBstop)
{
stopTask();
}
}
This is ** callAsynchronousTask()**
public void callAsynchronousTask() {
new PostDataAsyncTask().execute();
}
I am posting data twice. First time is when User click the START button and then I am start the timer to execute for every one min.
use purge() after cancel();
public void stopTask(){
if(doAsynchronousTask!=null){
Log.d("TIMER", "timer canceled");
handler.removeCallbacks(doAsynchronousTask);
// timer.cancel();
doAsynchronousTask.cancel();
doAsynchronousTask.purge();
}
}
You should stop the TimerTask first with: Timer.Cancel() and Timer.Purge().
you can change: handler.removeCallbacks(doAsynchronousTask); to removeCallbacksAndMessages(null).
Edit:
Look at your schedule code: timer.schedule(doAsynchronousTask, 0, 60000); --> that means you start your task immediately and repeated it after 60s.
When I see your onClickButton listener, there are 2 tasks which will be executed immediately. As a result, you cant cancel the tasks which are executed. To avoid it, you can call: timer.schedule(doAsynchronousTask, 60000, 60000);
I am a new develop of Android. I want to create an Application about time. The question is "how to call method every 30 second?"
Example: Every 30 second the application will send some message.
I do not know how to do it firstly, I use this function
time = new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
if(isDistanceStable()){
Toast.makeText(ChangeStatus.this, "Your speed is normal.", 3).show();
}else{
Toast.makeText(ChangeStatus.this, "Your speed is abnormal.", 3).show();
callManualRed();
}
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
time.cancel();
//intervalCheckDistance();
}
}.start();
}
but how to call it every 30 second. Please give me an example or some solutions to solve it. Thank you very much and Sorry with my English
cdt = new CountDownTimer(30000, 30000) {
public void onTick(long millisUntilFinished) {
// Method
}
public void onFinish() {
cdt.start(); // Call Again After 30 seconds
}
}.start();
Remember to call cdt.cancel(); when you want to end the timer
I have tried multiple ways to have a single persistent timer update the ui in multiple activities, and nothing seems to work. I have tried an AsyncTask, a Handler, and a CountDownTimer. The code below does not execute the first Log.i statement.... Is there a better way to start the timer (which must be called from another class) in Main (which is the only persistent class)?
public static void MainLawTimer()
{
MainActivity.lawTimer = new CountDownTimer(MainActivity.timeLeft, 1000)
{
public void onTick(long millisUntilFinished)
{
Log.i("aaa","Timer running. Time left: "+MainActivity.timeLeft);
MainActivity.timeLeft--;
if(MainActivity.timeLeft<=0)
{
//do stuff
}
else
{
//call method in another class
}
}
public void onFinish()
{ }
}.start();
}
To clarify my problem:
When I run the code the Log.i("aaa","Timer running") statement is never shown in the log, and the CountDownTimer never seems to start. MainLawTimer is called from another class only (not within the same class.
For CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
You can use a Handler
Handler m_handler;
Runnable m_handlerTask ;
int timeleft=100;
m_handler = new Handler();
#Override
public void run() {
if(timeleft>=0)
{
// do stuff
Log.i("timeleft",""+timeleft);
timeleft--;
}
else
{
m_handler.removeCallbacks(m_handlerTask); // cancel run
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
Timer
int timeleft=100;
Timer _t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
Log.i("timeleft",""+timeleft);
//update ui
}
});
if(timeleft>==0)
{
timeleft--;
}
else
{
_t.cancel();
}
}
}, 1000, 1000 );
You can use a AsyncTask or a Timer or a CountDownTimer.
Thank you all for your help, I discovered the error in my code... timeLeft was in seconds rather then milliseconds. Since timeLeft was under 1000 (the wait period) the timer never started.
I have this code where I want to try to send an e-mail report every hour (in the example to every second). If there is no coverage, try again within an hour etc. Somehow I managed to break the timer in sendUnsendedReports(): it fires only once. If I remove the call to sendUnsendedReports() than the timer is working perfectly. Even with the try-catch block around it, the timer only fires once. Please advice.
private void createAndScheduleSendReport() {
delayedSendTimer = new Timer();
delayedSendTimer.schedule(new TimerTask() {
#Override
public void run() {
Log.w("UrenRegistratie", "Try to send e-mail...");
try{
sendUnsendedReports();
}
catch(Exception e){
// added try catch block to be sure of uninterupted execution
}
Log.w("UrenRegistratie", "Mail scheduler goes to sleep.");
}
}, 0, 1000);
}
It seems that sometimes timer doesn't works well as it should be. The alternative of this is use of Handler instead TimerTask.
You can use it like :
private Handler handler = new Handler();
handler.postDelayed(runnable, 1000);
private Runnable runnable = new Runnable() {
#Override
public void run() {
try{
sendUnsendedReports();
}
catch(Exception e){
// added try catch block to be sure of uninterupted execution
}
/* and here comes the "trick" */
handler.postDelayed(this, 1000);
}
};
Check out this link for more detail. :)
schedule() can be called in various ways, depending on if you want the task to execute once, or periodically.
To execute the task only once:
timer.schedule(new TimerTask() {
#Override
public void run() {
}
}, 3000);
To execute the task every second after 3 s.
timer.schedule(new TimerTask() {
#Override
public void run() {
}
}, 3000, 1000);
More example usages can be found in the method headers
public void schedule(TimerTask task, Date when) {
// ...
}
public void schedule(TimerTask task, long delay) {
// ...
}
public void schedule(TimerTask task, long delay, long period) {
// ...
}
public void schedule(TimerTask task, Date when, long period) {
// ...
}
It is clearly that you hit the exception and get out of the Timer run method, thus interrupting the timer restart.