Timer should run One time but with different Intervals - android

I have a button on which I want to set the timer for 5 seconds for the first time and it should perform some task after completing 5 seconds. Also if user click button 2 times it should start timer for 10 seconds and after 10 seconds it should perform specific task. and if user click 3rd time it should stop all running timers. so I have do not know How to implement timer for one time
what I have search is this. But in this link it is continuously repeating after specific period of time, whereas I want to run once.
Now what I want
To start timer with first click (of 5 seconds)and if meanwhile user click 2nd time it should set timer with with new time period and if user click third time it cancels out all timers.
I do not want to use Thread timer using sleep method.
I want same behavior as there is in camera app in android 5.0 v.
So please tell me how to do this any code and source code would be appreciated.

In the link you provided you will find the answer if you try little harder.
For a repeating task:
new Timer().scheduleAtFixedRate(task, after, interval);
For a single run of a task:
new Timer().schedule(task, after);
So what you need to do is to maintain temporary variable to keep track of number of clicks and you can use second method like
For a repeating task:
new Timer().scheduleAtFixedRate(task, after, interval);
For a single run of a task:
new Timer().schedule(task, after * numberOfTimeBtnClked);
You have to pass the TimerTask method instead of task in that method.
**For updating your textview use below code and forget about whatever I have written above **
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//run in an interval of 1000ms
timer.schedule(timerTask, 0, 1000); //
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
timerSince++; //global integer variable with default value 0
if(timerSince == 5 * numberOfBtnClick){
//call your method
timer.cancel;
timerSince = 0;
}else{
//textView.setText(((5 * numberOfBtnClick)-timerSince)+" second left");
}
});
}
};
}
}
On event start button click call:
startTimer();

Related

Countdown timer in recycle view for online order

Hi there
I have a problem in my food orders app I want to create countdouwn timer in my recyclew view depends on start order time and finish after 2 minutes and after finish cancel the order ...
The problem is
1 - how to every order has a different timer from start order to 2 minutes
2 - how order timer still working even app is close and if app not open automatically cancel the order ...
android main
I am trying everything to do that but iam filed...
Iam reading about how to run countdouwn in background and also reading about how to display countdouwn timer in recyclew
But cant found solutions to my cases...
Any help please...
Use a class for example, Dish. Now have a member of that class named as cancelTimer or whatever you want to call it. Using Handler, make the countdown for that particular instance. This way you can have different timers for each of your dishes.
Example:
Dish dish1 = new Dish();
dish1.setCancelTimer(10000);
Handler h = new Handler();
h.postDelayed(new Runnable(){
public void run(){
dish1.setCancelTimer(dish1.getCancelTimer()-1000);
h.postDelayed(this, 1000);
}
}, 0);
Repeat for all other dishes like:
Dish dish2 = new Dish();
dish2.setCancelTimer(50000);
Handler h2 = new Handler();
h2.postDelayed(new Runnable(){
public void run(){
dish1.setCancelTimer(dish1.getCancelTimer()-1000);
h.postDelayed(this, 1000);
}
}, 0);

Create alarm automatically everytime Database gets new data

I need to create an alarm every time new data is inserted on the Database(the database has the values of date and time of every alarm that is going to be created), without any interaction with the user, the app has to do it automatically.
How do I know when new data is inserted? checking every x minutes using a timer?
How to create an alarm automatically when that happens?
Typically for something like this, you would want to use something more like Firebase that will live update your data.
But to do a timer, first extend TimerTask:
public class Progress extends TimerTask {
#Override
public void run(){
//this item runs on a separate thread
runOnUiThread(new Runnable() {
#Override
public void run() {
seconds += 0.1;
//this item runs on the main thread
}
});
}
}
And then to run this task:
Timer timer;
Progress progress;
timer.schedule(progress, 100, 100);
This will run the timer every .1 seconds.

Self Prepuating Timer That Modifies GUI in Android

I'm making an application and a certain part in my application I store a list of prices along with the time that the prices last for (they do not all last the same amount of time). So a price lasts a certain time then once that price's time is up it changes to another price (this part changes the UI or basically it updates a textview with the new price). So what I need is a timer that sets the timer again with the new time length and once it's done make the UI change. For instance say that each of the pairs represent the price amount and the time (in seconds): { {$2.53,1.4s}, {$4.57,4.45s}, {$1.23,3.6s}...}
So when the timer starts off the textview displays $2.53 and the timer lasts 1.4s and then it should grab the next price $4.57 and be set again but this time for 4.45s. This process continues on and on until the game is finished. I was thinking of using the CountDownTimer and resetting itself once the onFinish() method is called (I haven't verified if this idea works yet). Are there any other ideas?
You can use a countdown timer and onFinish method you call back the function and it starts another timer:
private void startWheatPrices(long gameTime)
{
//other stuff executed
StartWheatTimer(GameTimeDifference);//starts the timer for the first time
}
private void StartWheatTimer(long TimerAmount)
{
WheatTimer = new CountDownTimer(TimerAmount, 10) {
public void onTick(long millisUntilFinished)
{
}
public void onFinish()
{
//other stuff executed
WheatPricesTV.setText(Float.toString(PriceList.get(0).get(WheatPriceIndex).price));//price is changed
if(InGameplayMode)
StartWheatTimer(convertToMilliseconds(PriceList.get(0).get(WheatPriceIndex).timeLength));//call back the function to start the timer again
}
}.start();
}

How to stop the Timer in android? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm developing an application which sends a message to a specific number in a specific period of time. The problem is that it continues sending that message after that period of time. How would I stop the timer after that specific time in order to stop sending that message?
CountDownTimer waitTimer;
waitTimer = new CountDownTimer(60000, 300) {
public void onTick(long millisUntilFinished) {
//called every 300 milliseconds, which could be used to
//send messages or some other action
}
public void onFinish() {
//After 60000 milliseconds (60 sec) finish current
//if you would like to execute something when time finishes
}
}.start();
to stop the timer early:
if(waitTimer != null) {
waitTimer.cancel();
waitTimer = null;
}
and.. we must call "waitTimer.purge()" for the GC. If you don't use Timer anymore, "purge()" !! "purge()" removes all canceled tasks from the task queue.
if(waitTimer != null) {
waitTimer.cancel();
waitTimer.purge();
waitTimer = null;
}
In java.util.timer one can use .cancel() to stop the timer and clear all pending tasks.
We can schedule the timer to do the work.After the end of the time we set the message won't send.
This is the code.
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//here you can write the code for send the message
}
}, 10, 60000);
In here the method we are calling is,
public void scheduleAtFixedRate (TimerTask task, long delay, long period)
In here,
task : the task to schedule
delay: amount of time in milliseconds before first execution.
period: amount of time in milliseconds between subsequent executions.
For more information you can refer:
Android Developer
You can stop the timer by calling,
timer.cancel();
I had a similar problem: every time I push a particular button, I create a new Timer.
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
Exiting from that activity I deleted the timer:
if(my_timer!=null){
my_timer.cancel();
my_timer = null;
}
But it was not enough because the cancel() method only canceled the latest Timer. The older ones were ignored an didn't stop running. The purge() method was not useful for me.
I solved the problem just checking the Timer instantiation:
if(my_timer == null){
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
}
It says timer() is not available on android? You might find this article useful.
http://developer.android.com/resources/articles/timed-ui-updates.html
I was wrong. Timer() is available. It seems you either implement it the way it is one shot operation:
schedule(TimerTask task, Date when) // Schedule a task for single execution.
Or you cancel it after the first execution:
cancel() // Cancels the Timer and all scheduled tasks.
http://developer.android.com/reference/java/util/Timer.html
I had a similar problem and it was caused by the placement of the Timer initialisation.
It was placed in a method that was invoked oftener.
Try this:
Timer waitTimer;
void exampleMethod() {
if (waitTimer == null ) {
//initialize your Timer here
...
}
The "cancel()" method only canceled the latest Timer. The older ones were ignored an didn't stop running.

android timer question

Hello I am building an application that is going to execute a block of code at fixed periods of time (e.g. every 30 minutes). I would like that period to be strict,what I mean is that I would like to be guaranteed that the period will be 30 minutes and not 28 minutes or whenever the os whants to execute it.
I have a Timer object and use it as follows:
timer=new Timer();
timer.scheduleAtFixedRate(new GetLastLocation(), 0, this.getInterval());
where GetLastLocation is the handler class wich extends TimerTask.
This works fine,but I would like to be able to change the interval,what I am currently doing is using timer.scheduleAtFixedRate twice and changing the interval parameter to lets say a newInterval but I think that this is just having two timers execute every interval and new
Interval now, am I correct?
also I have tries cancelling the timer and then using the the method scheduleAtFixedRate() but this throws an exception as stated in the documentation.
what can I do to fix this?
regards maxsap
you can not schedule on a timer which was already cancelled or scheduled. You need to create a new timer for that.Timer timer;
synchronized void setupTimer(long duration){
if(timer != null) {
timer.cancel();
timer = null;
}
timer = new Timer();
timer.scheduleAtFixedRate(new GetLastLocation(), 0, duration);
}Now you can call setupTimer whenever you want to change the duration of the timer.PS: In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
Define your task inside a TimerTask (as you did) and schedule the timer.
public final void checkFunction(){
t = new Timer();
tt = new TimerTask() {
#Override
public void run() {
//Execute code...
}
};
t.schedule(tt, 10*1000); /* Run tt (your defined TimerTask)
again after 10 seconds. Change to your requested time. */
}
Just execute the function wherever you want, for example in onCreate or in onResume/onStart.
You can also use handler instead of timertask.
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if(what.msg==1)
{
what.msg==2;
}
}
};
mHandler.sendEmptyMessageDelayed(1, 10* 1000);//10*1000 10 sec.specify your time

Categories

Resources