How to restart Handler / Runnable on method call? The Next CEO of Stack OverflowHow do I efficiently iterate over each entry in a Java Map?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?Activity restart on rotation Android“implements Runnable” vs “extends Thread” in JavaWhy is the Android emulator so slow? How can we speed up the Android emulator?Can't create handler inside thread that has not called Looper.prepare()How do I convert a String to an int in Java?How do I fix android.os.NetworkOnMainThreadException?

How to get the last not-null value in an ordered column of a huge table?

Is there such a thing as a proper verb, like a proper noun?

It is correct to match light sources with the same color temperature?

Do scriptures give a method to recognize a truly self-realized person/jivanmukta?

Can Sneak Attack be used when hitting with an improvised weapon?

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Does the Idaho Potato Commission associate potato skins with healthy eating?

Airplane gently rocking its wings during whole flight

Can you teleport closer to a creature you are Frightened of?

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

Is there an equivalent of cd - for cp or mv

Which Pokemon have a special animation when running with them out of their pokeball?

How to avoid supervisors with prejudiced views?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Is it professional to write unrelated content in an almost-empty email?

What would be the main consequences for a country leaving the WTO?

Computationally populating tables with probability data

Why don't programming languages automatically manage the synchronous/asynchronous problem?

Strange use of "whether ... than ..." in official text

Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?

Man transported from Alternate World into ours by a Neutrino Detector

Yu-Gi-Oh cards in Python 3

Traveling with my 5 year old daughter (as the father) without the mother from Germany to Mexico

What flight has the highest ratio of timezone difference to flight time?



How to restart Handler / Runnable on method call?



The Next CEO of Stack OverflowHow do I efficiently iterate over each entry in a Java Map?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?Activity restart on rotation Android“implements Runnable” vs “extends Thread” in JavaWhy is the Android emulator so slow? How can we speed up the Android emulator?Can't create handler inside thread that has not called Looper.prepare()How do I convert a String to an int in Java?How do I fix android.os.NetworkOnMainThreadException?










0















I am using a method to instantiate a new Handler object and kicking off a method to do some task in the allocated time. The problem is, this timer is not restarted for each method call and any lingering time is continued with subsequent calls.



I am wondering how to fix this. This is my method:



private void doTask() 
viewModel.getFeedBackMessage().set("Calculating ...");
viewModel.fetchData();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
@Override
public void run()
if (viewModel.getData() == null)
viewModel.getFeedbackMessage().set("Failure.");
handler.removeCallbacks(this);
handler.postDelayed(this, 90000);
else
handler.removeCallbacks(this);
handler.postDelayed(this, 90000);



, 90000);



Edit:



new Thread(() -> 
int elapsedTime = 0;
while (elapsedTime < 90000)
try
Thread.sleep(1000);
catch (Exception ex)
if (currentLocation != null)
break;

elapsedTime += 1000;

).start();









share|improve this question



















  • 1





    Can you explain more? Why are you call remove callback and post delayed in both cases if/else. Removed is meant to cancel a future task or that future task is already being executed. So, the remove callback call is useless in my opinion.

    – Hichem BOUSSETTA
    Mar 8 at 18:06











  • Basically, if the data was found before the allocated time, I want to stop the Handler and if it doesn't find the data, then I still want to stop the Handler

    – Darnold14
    Mar 8 at 18:09











  • What you are posting is a delayed task that will be executed once instead you stop it before. But you can not stop the task inside the task itself. The remove callback has to be outside the delayed task, unless I am missing something.

    – Hichem BOUSSETTA
    Mar 8 at 18:19











  • How can I execute this timer task every method call?

    – Darnold14
    Mar 8 at 18:22






  • 1





    Okay I see. You are then using a wrong approach. In this type of scenario, you can use a do/while loop in which you check at each iteration if you have data available (this check must be short and non blocking), and then sleep the thread for some interval (let's say one second), after sleep you increment an elapsed integer variable that keeps track of total time you spent in the loop. If elapsed time is greater then your timeout value (90000), then you quit the loop. If inside the loop you receive data, you can then quit the loop using break.

    – Hichem BOUSSETTA
    Mar 8 at 18:51















0















I am using a method to instantiate a new Handler object and kicking off a method to do some task in the allocated time. The problem is, this timer is not restarted for each method call and any lingering time is continued with subsequent calls.



I am wondering how to fix this. This is my method:



private void doTask() 
viewModel.getFeedBackMessage().set("Calculating ...");
viewModel.fetchData();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
@Override
public void run()
if (viewModel.getData() == null)
viewModel.getFeedbackMessage().set("Failure.");
handler.removeCallbacks(this);
handler.postDelayed(this, 90000);
else
handler.removeCallbacks(this);
handler.postDelayed(this, 90000);



, 90000);



Edit:



new Thread(() -> 
int elapsedTime = 0;
while (elapsedTime < 90000)
try
Thread.sleep(1000);
catch (Exception ex)
if (currentLocation != null)
break;

elapsedTime += 1000;

).start();









share|improve this question



















  • 1





    Can you explain more? Why are you call remove callback and post delayed in both cases if/else. Removed is meant to cancel a future task or that future task is already being executed. So, the remove callback call is useless in my opinion.

    – Hichem BOUSSETTA
    Mar 8 at 18:06











  • Basically, if the data was found before the allocated time, I want to stop the Handler and if it doesn't find the data, then I still want to stop the Handler

    – Darnold14
    Mar 8 at 18:09











  • What you are posting is a delayed task that will be executed once instead you stop it before. But you can not stop the task inside the task itself. The remove callback has to be outside the delayed task, unless I am missing something.

    – Hichem BOUSSETTA
    Mar 8 at 18:19











  • How can I execute this timer task every method call?

    – Darnold14
    Mar 8 at 18:22






  • 1





    Okay I see. You are then using a wrong approach. In this type of scenario, you can use a do/while loop in which you check at each iteration if you have data available (this check must be short and non blocking), and then sleep the thread for some interval (let's say one second), after sleep you increment an elapsed integer variable that keeps track of total time you spent in the loop. If elapsed time is greater then your timeout value (90000), then you quit the loop. If inside the loop you receive data, you can then quit the loop using break.

    – Hichem BOUSSETTA
    Mar 8 at 18:51













0












0








0








I am using a method to instantiate a new Handler object and kicking off a method to do some task in the allocated time. The problem is, this timer is not restarted for each method call and any lingering time is continued with subsequent calls.



I am wondering how to fix this. This is my method:



private void doTask() 
viewModel.getFeedBackMessage().set("Calculating ...");
viewModel.fetchData();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
@Override
public void run()
if (viewModel.getData() == null)
viewModel.getFeedbackMessage().set("Failure.");
handler.removeCallbacks(this);
handler.postDelayed(this, 90000);
else
handler.removeCallbacks(this);
handler.postDelayed(this, 90000);



, 90000);



Edit:



new Thread(() -> 
int elapsedTime = 0;
while (elapsedTime < 90000)
try
Thread.sleep(1000);
catch (Exception ex)
if (currentLocation != null)
break;

elapsedTime += 1000;

).start();









share|improve this question
















I am using a method to instantiate a new Handler object and kicking off a method to do some task in the allocated time. The problem is, this timer is not restarted for each method call and any lingering time is continued with subsequent calls.



I am wondering how to fix this. This is my method:



private void doTask() 
viewModel.getFeedBackMessage().set("Calculating ...");
viewModel.fetchData();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
@Override
public void run()
if (viewModel.getData() == null)
viewModel.getFeedbackMessage().set("Failure.");
handler.removeCallbacks(this);
handler.postDelayed(this, 90000);
else
handler.removeCallbacks(this);
handler.postDelayed(this, 90000);



, 90000);



Edit:



new Thread(() -> 
int elapsedTime = 0;
while (elapsedTime < 90000)
try
Thread.sleep(1000);
catch (Exception ex)
if (currentLocation != null)
break;

elapsedTime += 1000;

).start();






java android multithreading






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 11 at 12:41







Darnold14

















asked Mar 8 at 17:37









Darnold14Darnold14

196




196







  • 1





    Can you explain more? Why are you call remove callback and post delayed in both cases if/else. Removed is meant to cancel a future task or that future task is already being executed. So, the remove callback call is useless in my opinion.

    – Hichem BOUSSETTA
    Mar 8 at 18:06











  • Basically, if the data was found before the allocated time, I want to stop the Handler and if it doesn't find the data, then I still want to stop the Handler

    – Darnold14
    Mar 8 at 18:09











  • What you are posting is a delayed task that will be executed once instead you stop it before. But you can not stop the task inside the task itself. The remove callback has to be outside the delayed task, unless I am missing something.

    – Hichem BOUSSETTA
    Mar 8 at 18:19











  • How can I execute this timer task every method call?

    – Darnold14
    Mar 8 at 18:22






  • 1





    Okay I see. You are then using a wrong approach. In this type of scenario, you can use a do/while loop in which you check at each iteration if you have data available (this check must be short and non blocking), and then sleep the thread for some interval (let's say one second), after sleep you increment an elapsed integer variable that keeps track of total time you spent in the loop. If elapsed time is greater then your timeout value (90000), then you quit the loop. If inside the loop you receive data, you can then quit the loop using break.

    – Hichem BOUSSETTA
    Mar 8 at 18:51












  • 1





    Can you explain more? Why are you call remove callback and post delayed in both cases if/else. Removed is meant to cancel a future task or that future task is already being executed. So, the remove callback call is useless in my opinion.

    – Hichem BOUSSETTA
    Mar 8 at 18:06











  • Basically, if the data was found before the allocated time, I want to stop the Handler and if it doesn't find the data, then I still want to stop the Handler

    – Darnold14
    Mar 8 at 18:09











  • What you are posting is a delayed task that will be executed once instead you stop it before. But you can not stop the task inside the task itself. The remove callback has to be outside the delayed task, unless I am missing something.

    – Hichem BOUSSETTA
    Mar 8 at 18:19











  • How can I execute this timer task every method call?

    – Darnold14
    Mar 8 at 18:22






  • 1





    Okay I see. You are then using a wrong approach. In this type of scenario, you can use a do/while loop in which you check at each iteration if you have data available (this check must be short and non blocking), and then sleep the thread for some interval (let's say one second), after sleep you increment an elapsed integer variable that keeps track of total time you spent in the loop. If elapsed time is greater then your timeout value (90000), then you quit the loop. If inside the loop you receive data, you can then quit the loop using break.

    – Hichem BOUSSETTA
    Mar 8 at 18:51







1




1





Can you explain more? Why are you call remove callback and post delayed in both cases if/else. Removed is meant to cancel a future task or that future task is already being executed. So, the remove callback call is useless in my opinion.

– Hichem BOUSSETTA
Mar 8 at 18:06





Can you explain more? Why are you call remove callback and post delayed in both cases if/else. Removed is meant to cancel a future task or that future task is already being executed. So, the remove callback call is useless in my opinion.

– Hichem BOUSSETTA
Mar 8 at 18:06













Basically, if the data was found before the allocated time, I want to stop the Handler and if it doesn't find the data, then I still want to stop the Handler

– Darnold14
Mar 8 at 18:09





Basically, if the data was found before the allocated time, I want to stop the Handler and if it doesn't find the data, then I still want to stop the Handler

– Darnold14
Mar 8 at 18:09













What you are posting is a delayed task that will be executed once instead you stop it before. But you can not stop the task inside the task itself. The remove callback has to be outside the delayed task, unless I am missing something.

– Hichem BOUSSETTA
Mar 8 at 18:19





What you are posting is a delayed task that will be executed once instead you stop it before. But you can not stop the task inside the task itself. The remove callback has to be outside the delayed task, unless I am missing something.

– Hichem BOUSSETTA
Mar 8 at 18:19













How can I execute this timer task every method call?

– Darnold14
Mar 8 at 18:22





How can I execute this timer task every method call?

– Darnold14
Mar 8 at 18:22




1




1





Okay I see. You are then using a wrong approach. In this type of scenario, you can use a do/while loop in which you check at each iteration if you have data available (this check must be short and non blocking), and then sleep the thread for some interval (let's say one second), after sleep you increment an elapsed integer variable that keeps track of total time you spent in the loop. If elapsed time is greater then your timeout value (90000), then you quit the loop. If inside the loop you receive data, you can then quit the loop using break.

– Hichem BOUSSETTA
Mar 8 at 18:51





Okay I see. You are then using a wrong approach. In this type of scenario, you can use a do/while loop in which you check at each iteration if you have data available (this check must be short and non blocking), and then sleep the thread for some interval (let's say one second), after sleep you increment an elapsed integer variable that keeps track of total time you spent in the loop. If elapsed time is greater then your timeout value (90000), then you quit the loop. If inside the loop you receive data, you can then quit the loop using break.

– Hichem BOUSSETTA
Mar 8 at 18:51












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068290%2fhow-to-restart-handler-runnable-on-method-call%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068290%2fhow-to-restart-handler-runnable-on-method-call%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived