How to restart Handler / Runnable on method call? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!How 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 widely used is the term Treppenwitz? Is it something that most Germans know?

Dating a Former Employee

What is a non-alternating simple group with big order, but relatively few conjugacy classes?

What's the meaning of 間時肆拾貳 at a car parking sign

Generate an RGB colour grid

Is the Standard Deduction better than Itemized when both are the same amount?

What exactly is a "Meth" in Altered Carbon?

Can a non-EU citizen traveling with me come with me through the EU passport line?

English words in a non-english sci-fi novel

Coloring maths inside a tcolorbox

Is it fair for a professor to grade us on the possession of past papers?

Why did the rest of the Eastern Bloc not invade Yugoslavia?

Should I use a zero-interest credit card for a large one-time purchase?

How to find all the available tools in mac terminal?

Single word antonym of "flightless"

Using et al. for a last / senior author rather than for a first author

Why do people hide their license plates in the EU?

If a contract sometimes uses the wrong name, is it still valid?

Overriding an object in memory with placement new

How do pianists reach extremely loud dynamics?

What does an IRS interview request entail when called in to verify expenses for a sole proprietor small business?

Output the ŋarâþ crîþ alphabet song without using (m)any letters

Why do we bend a book to keep it straight?

Using audio cues to encourage good posture



How to restart Handler / Runnable on method call?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!How 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?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








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

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved