I have a requirement, where I need to create a timer task which will execute the function after every 10 sec. There is reset Button, on click of that reset Button I want to reset my time from 10 sec to 30 sec. Now after 30 sec when it execute the function I need to reset my timer again to 10 sec. I tried using Handler , TimerTask and CountDownTimer, but not able to achieve the requirement. Can anyone suggest me the best way of solving this problem
// OnCreate of Activity
if (timerInstance == null) {
timerInstance = Timer()
timerInstance?.schedule(createTimerTask(), 10000L, 10000L)
}
private fun createTimerTask(): TimerTask {
return object : TimerTask() {
override fun run() {
Log.d("TimerTask", "Executed")
//presenter?.onCountdownTimerFinished(adapter.activeCallList, adapter.previousPosition)
}
}
}
//On Reset Button Click
timerInstance?.cancel()
timerInstance = Timer()
timerInstance?.schedule(createTimerTask(), 30000L, 30000L)
When your button is pressed, you could cancel the submitted TimerTask and reschedule with a delay of 30sec and a period of 10sec ?
https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html#scheduleAtFixedRate-java.util.TimerTask-long-long-
Cancel the first submitted task by calling .cancel on it.
use 30000L, 10000L as delay and period on the schedule in the button
Example code :
package so20190423;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
public static void main(String[] args) {
System.out.println(new Date());
Timer timer = new Timer();
TimerTask task = newTask();
timer.scheduleAtFixedRate(task, 10000L, 10000L);
task.cancel();
timer.scheduleAtFixedRate( newTask(), 30000L, 10000L);
}
protected static TimerTask newTask() {
return new TimerTask() {
#Override
public void run() {
System.out.println("YO");
System.out.println(new Date());
}
};
}
}
HTH!
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);
I am using a timer that should every 12 seconds issues a warning. as shown in the code below i set the delay to 0 so that the timer starts immediately, but at
run time, the below posted timer does not starts immediately it waits for the period set as a delay despit i set the delay to 0
in other words, the below timer should wait 0 sec as a delay and repeats itself every 12 seconds but what happens is, it at initial execution it waits 12 sec and repeat itself every 12 sec
any logical explaination why that is happening
code:
mVelWarningRule1Timer.scheduleAtFixedRate(
new SpeakOut(
getApplicationContext(),
getApplicationContext()
.getResources()
.getString(R.string.rule_velocity_1)),
0,
getApplicationContext()
.getResources()
.getInteger(R.integer.int_assistWarning_interval)
);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new RemindTask(), 0, 12000);
The first is the internal class. The second parameter is the delay. The third gives you the interval.
private class RemindTask extends TimerTask {
#Override
public void run() {
try
{
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (page > adapter.getCount()) {
page = 0;
} else {
viewPager.setCurrentItem(page++, true);
}
}
});
}
catch(Exception e)
{
timer.cancel();
}
}
}
This would make a carousel of pictures change every 12 seconds
The timer should work non stop once i start my program with one second interval.
At the top of my MainActivity i added:
import java.util.Timer;
Then in the MainActivity class:
public class MainActivity extends ActionBarActivity
I added:
private Timer timer = new Timer();
Now i have the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
How can i make that the timer will start working once i'm starting my program with interval of a second ?
First you need to import:
import java.util.Timer;
import java.util.TimerTask;
After this you need to setup your timer like this:
//Declare the timer
Timer myTimer = new Timer();
//Set the schedule function and rate
myTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Called at every 1000 milliseconds (1 second)
Log.i("MainActivity", "Repeated task");
}
},
//set the amount of time in milliseconds before first execution
0,
//Set the amount of time between each execution (in milliseconds)
1000);
You can start the timer with one of the schedule methods like this:
timer.schedule(new TimerTask() {
#Override
public void run() {
//do your stuff here...
}
}, 0, 1000);
This will start your timer with a delay of 0 milliseconds and repeat it after 1000 milliseconds.
You should read at least the heading of the javadoc here: java.util.Timer.
I don't know that much about the Android platform but you have to be cautious using threading. Read about this here: https://developer.android.com/guide/components/processes-and-threads.html#Threads
Set the interval to 1000, because the interval in timers are based on milliseconds, so 1000 milliseconds = 1 second.
try searching for the property "Interval" in the properties tab, because i use netbeans and there is interval on side, and the command to be put on the Timer_Tick event to make sure the command is done everytime the interval happens which is every second
How do I make my Timer Task run more than once? This is really bothering me..
timer = new Timer();
timer.schedule(new Client(), 1000);
public void run() {
try {
System.out.println("sent data");
socketOut.write(0);
} catch (Exception e) {
// disconnect client on their side
Game.destroyGame();
timer.cancel();
timer.purge();
}
}
I want this timer to run for an infinite amount of time until the Exception occurs.
When the Javadoc says that it repeats with a specific delay, the delay is the initial delay before the TimerTask starts and not for how long the TimerTask will run. You can repeat the task every period milliseconds. Look at the schedule method. Below is a simple example that repeats every 2 seconds, indefinitely. In the example, the call:
timer.schedule(new RemindTask(seconds), 0, seconds * 1000);
tells timer to run the RemindTask every seconds seconds (*1000 because the time here is really in miliseconds), with an initial delay of 0 - i.e. start the RemindTask right away and then keep repeating at regular intervals.
import java.util.Timer;
import java.util.TimerTask;
public class Main {
static Timer timer;
static int i = 0;
class RemindTask extends TimerTask {
private int seconds;
public RemindTask(int seconds) {
this.seconds = seconds;
}
public void run() {
i+= seconds ;
System.out.println(i + " seconds!");
}
}
public Main(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(seconds), 0, seconds * 1000);
}
public static void main(String args[]) {
new Main(2);
System.out.format("Task scheduled.%n");
}
}
Looks like to me you're running a GUI program (I'm assuimg SWING, because your other question you were using SWING). So here's a bit of advice. Use a javax.swing.Timer for Swing program.
"How do I make my Timer Task run more than once? "
javax.swing.Timer has methods .stop() and .start() and .restart(). A basic implementation of the Timer object is something like this
Timer timer = new Timer(delay, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
timer.start();
You can do anything you want in the actionPerformed and it will fire an event every how many ever milliseconds you provide to the delay. You can have a button call .start() or .stop()
See this answer for a simple implementation of Timer imitating a sort of stop watch for a Boggle game
I am using java.util.Timer class and I am using its schedule method to perform some task, but after executing it for 6 times I have to stop its task.
How should I do that?
Keep a reference to the timer somewhere, and use:
timer.cancel();
timer.purge();
to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.
private static int count = 0;
public static void run() {
count++;
if (count >= 6) {
timer.cancel();
timer.purge();
return;
}
... perform task here ....
}
Either call cancel() on the Timer if that's all it's doing, or cancel() on the TimerTask if the timer itself has other tasks which you wish to continue.
You should stop the task that you have scheduled on the timer:
Your timer:
Timer t = new Timer();
TimerTask tt = new TimerTask() {
#Override
public void run() {
//do something
};
};
t.schedule(tt,1000,1000);
In order to stop:
tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread
Notice that just cancelling the timer will not terminate ongoing timertasks.
Terminate the Timer once after awake at a specific time in milliseconds.
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);