What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java? - java

Can anyone tell me if an equivalent for setInterval/setTimeout exists for Android? Does anybody have any example about how to do it?

As always with Android there's lots of ways to do this, but assuming you simply want to run a piece of code a little bit later on the same thread, I use this:
new android.os.Handler(Looper.getMainLooper()).postDelayed(
new Runnable() {
public void run() {
Log.i("tag", "This'll run 300 milliseconds later");
}
},
300);
.. this is pretty much equivalent to
setTimeout(
function() {
console.log("This will run 300 milliseconds later");
},
300);

setInterval()
function that repeats itself in every n milliseconds
Javascript
setInterval(function(){ Console.log("A Kiss every 5 seconds"); }, 5000);
Approximate java Equivalent
new Timer().scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
Log.i("tag", "A Kiss every 5 seconds");
}
},0,5000);
setTimeout()
function that works only after n milliseconds
Javascript
setTimeout(function(){ Console.log("A Kiss after 5 seconds"); },5000);
Approximate java Equivalent
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Log.i("tag","A Kiss after 5 seconds");
}
}, 5000);

If you're not worried about waking your phone up or bringing your app back from the dead, try:
// Param is optional, to run task on UI thread.
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
#Override
public void run() {
// Do the task...
handler.postDelayed(this, milliseconds) // Optional, to repeat the task.
}
};
handler.postDelayed(runnable, milliseconds);
// Stop a repeating task like this.
handler.removeCallbacks(runnable);

Depending on what you actually want to achieve, you should take a look at Android Handlers:
http://developer.android.com/reference/android/os/Handler.html
If you previously used javascript setTimeout() etc to schedule a task to run in the future, this is the Android way of doing it (postDelayed / sendMessageDelayed).
Note that neither Handlers or Timers makes an Android phone wake up from sleep mode. In other words, if you want to schedule something to actually happen even though the screen is off / cpu is sleeping, you need to check out the AlarmManager too.

The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:
this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

I do not know much about JavaScript, but I think Timers may be what you are looking for.
http://developer.android.com/reference/java/util/Timer.html
From the link:
One-shot are scheduled to run at an absolute time or after a relative delay. Recurring tasks are scheduled with either a fixed period or a fixed rate.

import java.util.Timer;
import java.util.TimerTask;
class Clock {
private Timer mTimer = new Timer();
private int mSecondsPassed = 0;
private TimerTask mTask = new TimerTask() {
#Override
public void run() {
mSecondsPassed++;
System.out.println("Seconds passed: " + mSecondsPassed);
}
};
private void start() {
mTimer.scheduleAtFixedRate(mTask, 1000, 1000);
}
public static void main(String[] args) {
Clock c = new Clock();
c.start();
}
}

I was creating a mp3 player for android, I wanted to update the current time every 500ms so I did it like this
setInterval
private void update() {
new android.os.Handler().postDelayed(new Runnable() {
#Override
public void run() {
long cur = player.getCurrentPosition();
long dur = player.getDuration();
currentTime = millisecondsToTime(cur);
currentTimeView.setText(currentTime);
if (cur < dur) {
updatePlayer();
}
// update seekbar
seekBar.setProgress( (int) Math.round((float)cur / (float)dur * 100f));
}
}, 500);
}
which calls the same method recursively

Here's a setTimeout equivalent, mostly useful when trying to update the User Interface
after a delay.
As you may know, updating the user interface can only by done from the UI thread.
AsyncTask does that for you by calling its onPostExecute method from that thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Update the User Interface
}
}.execute();

As always with Android there's lots of ways to do this, but assuming you simply want to run a piece of code on the same thread, I use this:
new Timer().scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
Log.i("tag", "Hai Codemaker");
}
},0,1000);
This code will log Hai Codemaker text every one second.

Kotlin:
You can also use CountDownTimer:
class Timer {
companion object {
#JvmStatic
fun call(ms: Long, f: () -> Unit) {
object : CountDownTimer(ms,ms){
override fun onFinish() { f() }
override fun onTick(millisUntilFinished: Long) {}
}.start()
}
}
}
And in your code:
Timer.call(5000) { /*Whatever you want to execute after 5000 ms*/ }

In case someone wants -
Kotlin equivalent to JavaScript setInterval/setTimeout
IMPORTANT: Remember to import android.os.Handler. Don't get mistaken by java.util.logging.Handler
Timeout equivalent
Javascript: setTimeout()
setTimeout(function(){
// something that can be run.
}, 1500);
Kotlin: runOnTimeout()
inline fun runOnTimeout(crossinline block: () -> Unit, timeoutMillis: Long) {
Handler(Looper.getMainLooper()).postDelayed({
block()
}, timeoutMillis)
}
Kotlin: Calling
runOnTimeout({
// something that can be run.
}, 1500)
Timeinterval equivalent
Javascript: setInterval()
setInterval(function(){
// something that can be run.
}, 1500);
Kotlin: runOnInterval()
inline fun runOnInterval(crossinline block: () -> Unit, interval: Long) {
val runnable = object : Runnable {
override fun run() {
block()
handler.postDelayed(this, interval)
}
}
handler.post(runnable)
}
Kotlin: Calling
runOnInterval({
// something that can be run.
}, 1500)
Cancellable timeout and interval
If you want to use custom handler so that you can cancel the runnable, then you can use following codes.
Timeout
inline fun runOnTimeout(crossinline block: () -> Unit, timeoutMillis: Long) {
runOnTimeout(Handler(Looper.getMainLooper()), block, timeoutMillis)
}
inline fun runOnTimeout(handler: Handler, crossinline block: () -> Unit, timeoutMillis: Long): Runnable {
val runnable = Runnable { block() }
handler.postDelayed(runnable, timeoutMillis)
return runnable
}
Timeout: Calling
runOnTimeout({
// something that can be run.
}, 1500)
// OR
val runnable = runOnTimeout(mHandler, {
// something that can be run.
}, 1500)
// to cancel
mHandler.removeCallbacks(runnable)
Interval
inline fun runOnInterval(crossinline block: () -> Unit, interval: Long) {
runOnInterval(Handler(Looper.getMainLooper()), block, interval)
}
inline fun runOnInterval(handler: Handler, crossinline block: () -> Unit, interval: Long): Runnable {
val runnable = object : Runnable {
override fun run() {
block()
handler.postDelayed(this, interval)
}
}
handler.post(runnable)
return runnable
}
Interval: Calling
runOnInterval({
// something that can be run.
}, 1500)
// OR
val runnable = runOnInterval(mHandler, {
// something that can be run.
}, 1500)
// to cancel
mHandler.removeCallbacks(runnable)

Related

How to terminate a process after a certain time? [duplicate]

How to set a Timer, say for 2 minutes, to try to connect to a Database then throw exception if there is any issue in connection?
So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.
Setting a timer
First you need to create a Timer (I'm using the java.util version here):
import java.util.Timer;
..
Timer timer = new Timer();
To run the task once you would do:
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your database code here
}
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* your database code here */, 2*60*1000);
To have the task repeat after the duration you would do:
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Your database code here
}
}, 2*60*1000, 2*60*1000);
// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);
Making a task timeout
To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
#Override
public void run() {
// Database task
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.
One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.
Use this
long startTime = System.currentTimeMillis();
long elapsedTime = 0L.
while (elapsedTime < 2*60*1000) {
//perform db poll/check
elapsedTime = (new Date()).getTime() - startTime;
}
//Throw your exception
Ok, I think I understand your problem now. You can use a Future to try to do something and then timeout after a bit if nothing has happened.
E.g.:
FutureTask<Void> task = new FutureTask<Void>(new Callable<Void>() {
#Override
public Void call() throws Exception {
// Do DB stuff
return null;
}
});
Executor executor = Executors.newSingleThreadScheduledExecutor();
executor.execute(task);
try {
task.get(5, TimeUnit.SECONDS);
}
catch(Exception ex) {
// Handle your exception
}
new java.util.Timer().schedule(new TimerTask(){
#Override
public void run() {
System.out.println("Executed...");
//your code here
//1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly
}
},1000*5,1000*5);
[Android] if someone looking to implement timer on android using java.
you need use UI thread like this to perform operations.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
ActivityName.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// do something
}
});
}
}, 2000));

I want timer/handler or something else to run some specific function twice?

When I start the app "specific function" needs to be executed.
After 10 seconds "specific function" needs to be triggered again.
After this second operation "specific function" should not triggered again.
There are two way to handle your problem.
If there is any condition you want to check and accordingly do the work after every 10 seconds You should Use a Handler.
If there is no condition on anything and you just want to run the code after every 10 Seconds. Then TimerTask is also one way. I have actually worked with TimerTask class. So i say it is quite easy.
Creating your class and implementing the methods.
class myTaskTimer extends TimerTask{
#Override
public void run() {
Log.e("TAG", "run: "+"timer x");
}
}
and now in your code Create a new Timer Object and initialize it.
Timer t = new Timer();
Now you can schedule your task in it after a specified interval like below:
t.scheduleAtFixedRate(new myTaskTimer(),10000,10000);
The function is explained below:
void scheduleAtFixedRate (TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution,
beginning after the specified delay. Subsequent executions take place
at approximately regular intervals, separated by the specified period.
and now for handler , below is the code and it can check for any condition. Code taken from here for your help.
private int mInterval = 10000; // 10 seconds as you need
private Handler mHandler;
#Override
protected void onCreate(Bundle bundle) {
// your code here
mHandler = new Handler();
startRepeatingTask();
}
#Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
try {
updateStatus(); //this function can change value of mInterval.
} finally {
// 100% guarantee that this always happens, even if
// your update method throws an exception
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
I hope it helps.
Use android.os.Handler as per #pskink comment.
private void callSomeMethodTwice(){
context.myMethod(); //calling 1st time
new Handler().postDelayed(new Runnable(){
#Override
public void run(){
context.myMethod(); //calling 2nd time after 10 sec
}
},10000};
}

Convert indefinitely running Runnable from java to kotlin

I have some code like this in java that monitors a certain file:
private Handler mHandler = new Handler();
private final Runnable monitor = new Runnable() {
public void run() {
// Do my stuff
mHandler.postDelayed(monitor, 1000); // 1 second
}
};
This is my kotlin code:
private val mHandler = Handler()
val monitor: Runnable = Runnable {
// do my stuff
mHandler.postDelayed(whatToDoHere, 1000) // 1 second
}
I dont understand what Runnable I should pass into mHandler.postDelayed. What is the right solution? Another interesting thing is that the kotlin to java convertor freezes when I feed this code.
Lambda-expressions do not have this, but object expressions (anonymous classes) do.
object : Runnable {
override fun run() {
handler.postDelayed(this, 1000)
}
}
A slightly different approach which may be more readable
val timer = Timer()
val monitor = object : TimerTask() {
override fun run() {
// whatever you need to do every second
}
}
timer.schedule(monitor, 1000, 1000)
From: Repeat an action every 2 seconds in java
Lambda-expressions do not have this, but object expressions (anonymous classes) do. Then the corrected code would be:
private val mHandler = Handler()
val monitor: Runnable = object : Runnable{
override fun run() {
//any action
}
//runnable
}
mHandler.postDelayed(monitor, 1000)
runnable display Toast Message "Hello World every 4 seconds
//Inside a class main activity
val handler: Handler = Handler()
val run = object : Runnable {
override fun run() {
val message: String = "Hello World" // your message
handler.postDelayed(this, 4000)// 4 seconds
Toast.makeText(this#MainActivity,message,Toast.LENGTH_SHORT).show() // toast method
}
}
handler.post(run)
}
var handler=Handler()
handler.postDelayed(Runnable { kotlin.run {
// enter code here
} },2000)

How do I use a timer to run code again and again until a boolean value e.g. Testing is equal to true?

This is probably a very easy question but, How do I use a timer to run code again and again until a boolean value e.g. Testing is equal to true?
Obviously I would use a while loop but I don't want it to stop the rest of the work taking place on the main ui thread
If your process is running simultaneously, use a Handler and use its postDelayed(Runnable, long) to post a callback implementing the Runnable interface.
A rather naive example:
final handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
if (<EXPRESSION>) {
// Evaluated true, do your stuff and exit the polling loop.
} else {
handler.postDelayed(this, <TIMEOUT>);
}
}
handler.postDelayed(r, <TIMEOUT>);
You can use AlarmManager class to manage your thread. its simple to use.
for more info you can visit Android SDK Doc
timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Do your task
if(flagIsOn)
{
timer.cancel();
timer.purge();
}
}
}, 0, 1000);

How to set a Timer in Java?

How to set a Timer, say for 2 minutes, to try to connect to a Database then throw exception if there is any issue in connection?
So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.
Setting a timer
First you need to create a Timer (I'm using the java.util version here):
import java.util.Timer;
..
Timer timer = new Timer();
To run the task once you would do:
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your database code here
}
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* your database code here */, 2*60*1000);
To have the task repeat after the duration you would do:
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Your database code here
}
}, 2*60*1000, 2*60*1000);
// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);
Making a task timeout
To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
#Override
public void run() {
// Database task
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.
One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.
Use this
long startTime = System.currentTimeMillis();
long elapsedTime = 0L.
while (elapsedTime < 2*60*1000) {
//perform db poll/check
elapsedTime = (new Date()).getTime() - startTime;
}
//Throw your exception
Ok, I think I understand your problem now. You can use a Future to try to do something and then timeout after a bit if nothing has happened.
E.g.:
FutureTask<Void> task = new FutureTask<Void>(new Callable<Void>() {
#Override
public Void call() throws Exception {
// Do DB stuff
return null;
}
});
Executor executor = Executors.newSingleThreadScheduledExecutor();
executor.execute(task);
try {
task.get(5, TimeUnit.SECONDS);
}
catch(Exception ex) {
// Handle your exception
}
new java.util.Timer().schedule(new TimerTask(){
#Override
public void run() {
System.out.println("Executed...");
//your code here
//1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly
}
},1000*5,1000*5);
[Android] if someone looking to implement timer on android using java.
you need use UI thread like this to perform operations.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
ActivityName.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// do something
}
});
}
}, 2000));

Categories

Resources