Reputation: 14707
I have a Thread which I wants to run after every 15 minute. Currently I am calling this thread from another class like
Class B{
public void start(){
while(true){
new Thread(new A()).start();
}
}
}
Class A implements Runnable{
@override
public void run(){
//some operation
}
}
How can I invoke Thread A on every 15 minute.
Upvotes: 4
Views: 2869
Reputation: 8956
alternate options use class java.util.Timer
Timer time = new Timer();
ScheduledTask st = new ScheduledTask();
time.schedule(st, 0, 15000);
or
public void scheduleAtFixedRate(TimerTask task,long delay,long period);
Or even
java.util.concurrent.ScheduledExecutorService
's methods
schedule(Runnable command, long delay, TimeUnit unit)
Upvotes: 2
Reputation: 46871
You can use Timer
or ScheduledExecutorService
to repeat a task at an interval.
An
ExecutorService
that can schedule commands to run after a given delay, or to execute periodically.
sample code:
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
}, 0, 15, TimeUnit.MINUTES);
Find more examples...
Upvotes: 5
Reputation: 11030
I think a Timer
will do ya.
import java.util.Timer;
import java.util.TimerTask;
class A extends TimerTask {
@Override
public void run(){
//some operation
}
}
A task = new A();
final long MINUTES = 1000 * 60;
Timer timer = new Timer( true );
timer.schedule(task, 15 * MINUTES, 15 * MINUTES);
Upvotes: 0
Reputation: 8240
Look at classes Timer and TimerTask.
A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
Upvotes: 3
Reputation: 12196
When started it can't start again.
You can put Thread.Sleep(15*60*1000)
inside the run
function in order to make it sleep and surround it with while in order to loop again.
Upvotes: 0
Reputation: 36304
use sleep like this:
public void run(){
while(true){
// some code
try{
Thread.sleep(15*60*1000) // sleep for 15 minutes
}
catch(InterruptedException e)
{
}
}
}
Upvotes: 2