java: run a function after a specific number of seconds
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
}
},
5000
);
EDIT:
javadoc says:
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.
How to execute a method after specific seconds for multiple time
You can also use ScheduledExecutorService to achieve this. You need to invoke the scheduleAtFixedRate
method of the executor service. Check the snippet below
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class SchedulerExample {
// counter to keep track of how many times thread has run
static AtomicInteger runTimeCounter = new AtomicInteger(1);
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
int totalCountToRun = 3;
int threadSleepTime = 4;
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (runTimeCounter.get() <= totalCountToRun) {
System.out.println("Hello");
System.out.println("Thread will sleep for " + threadSleepTime + " Seconds now");
incrementRunTimeCounter();
} else {
System.out.println("Have finished running for " + totalCountToRun + " times ..." +
"Will exit now from the application ...");
System.exit(0);
}
}
}, 0, threadSleepTime, TimeUnit.SECONDS);
}
static void incrementRunTimeCounter() {
System.out.println(Thread.currentThread().getName() + " incrementing it to: " +
runTimeCounter.getAndIncrement());
}
}
You may change the initialDelay
and period
parameter depending on the use case.
Have used the concept of AtomicInteger
to increment the number of times the thread has executed. Keep a conditional check on this counter in run method to ensure it runs only for the number of times you want it to run. You can change the totalCountToRun
variable depending on your use case.
Call method after some delay in java
Use Timer and TimerTask
create a member variable of type Timer
in YourClassType
lets say: private Timer timer = new Timer();
and your method will look something like this:
public synchronized void abcCaller() {
this.timer.cancel(); //this will cancel the current task. if there is no active task, nothing happens
this.timer = new Timer();
TimerTask action = new TimerTask() {
public void run() {
YourClassType.abc(); //as you said in the comments: abc is a static method
}
};
this.timer.schedule(action, 60000); //this starts the task
}
Execute function after 5 seconds in Android
You can use the Handler to add some delay.Call the method displayData()
as below so that it will be executed after 5 seconds.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
displayData();
}
}, 5000);
Note : Do not use the threads like Thread.sleep(5000);
because it will block your UI and and makes it irresponsive.
Related Topics
Getoutputstream() Has Already Been Called for This Response
How to Change JPAnel Inside a Jframe on the Fly
How to Iterate an Arraylist Inside a Hashmap Using Jstl
How to Understand Happens-Before Consistent
Is Java.Time Failing to Parse Fraction-Of-Second
Why Is the Catch(Exception) Almost Always a Bad Idea
What Is a Class Literal in Java
MAC Os X and Multiple Java Versions
Covariance, Invariance and Contravariance Explained in Plain English
Different Between Parseint() and Valueof() in Java
Convert a Byte Array to Integer in Java and Vice Versa
Good Hash Function for Strings
Android M Permissions: Onrequestpermissionsresult() Not Being Called
How to Convert Int[] to Integer[] in Java
How to View My Realm File in the Realm Browser
Createprocess Error=206, the Filename or Extension Is Too Long When Running Main() Method