Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep running a Thread after specific time

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.

like image 743
Ashish Avatar asked Dec 20 '22 12:12

Ashish


2 Answers

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...

like image 83
Braj Avatar answered Jan 06 '23 09:01

Braj


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.

like image 33
pgiecek Avatar answered Jan 06 '23 07:01

pgiecek