Como agendar uma tarefa periódica em Java?

Preciso de agendar uma tarefa para executar num intervalo de tempo fixo. Como posso fazer isso com suporte de intervalos longos (por exemplo em cada 8 horas)?

estou a usar {[[0]}. O {[[0]} suporta intervalos de tempo longos?

Author: Joachim Sauer, 2011-10-18

11 answers

Utilize um Serviço escalonado:

 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
 scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);
 278
Author: b_erb, 2015-04-29 23:31:42

Você deve dar uma olhada em Quartzo é um framework java que trabalha com as edições EE e SE e permite definir tarefas para executar um tempo específico

 48
Author: Jorge, 2011-10-18 21:41:05

Tenta por aqui - >

Em primeiro lugar, crie um horário de classe que execute a sua tarefa, e parece:
public class CustomTask extends TimerTask  {

   public CustomTask(){

     //Constructor

   }

   public void run() {
       try {

         // Your task process

       } catch (Exception ex) {
           System.out.println("error running thread " + ex.getMessage());
       }
    }
}

Então, na classe principal, você instancia a tarefa e executa-a periodicamente, iniciada por uma data especificada:

 public void runTask() {

        Calendar calendar = Calendar.getInstance();
        calendar.set(
           Calendar.DAY_OF_WEEK,
           Calendar.MONDAY
        );
        calendar.set(Calendar.HOUR_OF_DAY, 15);
        calendar.set(Calendar.MINUTE, 40);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);



        Timer time = new Timer(); // Instantiate Timer Object

        // Start running the task on Monday at 15:40:00, period is set to 8 hours
        // if you want to run the task immediately, set the 2nd parameter to 0
        time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
}
 24
Author: Shessuky, 2018-11-08 11:02:54

Utilize o Google Guava AbstractScheduledService da seguinte forma:

public class ScheduledExecutor extends AbstractScheduledService {

   @Override
   protected void runOneIteration() throws Exception {
      System.out.println("Executing....");
   }

   @Override
   protected Scheduler scheduler() {
        return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
   }

   @Override
   protected void startUp() {
       System.out.println("StartUp Activity....");
   }


   @Override
   protected void shutDown() {
       System.out.println("Shutdown Activity...");
   }

   public static void main(String[] args) throws InterruptedException {
       ScheduledExecutor se = new ScheduledExecutor();
       se.startAsync();
       Thread.sleep(15000);
       se.stopAsync();
   }
}
Se tiver mais serviços como este, registar todos os serviços no ServiceManager será bom, uma vez que todos os serviços podem ser iniciados e interrompidos em conjunto. Leia aqui para mais sobre ServiceManager.
 14
Author: Aride Chettali, 2020-08-26 11:48:35

Se quiser continuar com {[[0]}, pode usá-lo para agendar em intervalos de tempo grandes. Você simplesmente passa no período que você está procurando. Verifique a documentação aqui.

 10
Author: Belizzle, 2011-10-19 12:42:04

Uso a funcionalidade da mola. (contexto de primavera jar ou dependência de maven).

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Component
public class ScheduledTaskRunner {

    @Autowired
    @Qualifier("TempFilesCleanerExecution")
    private ScheduledTask tempDataCleanerExecution;

    @Scheduled(fixedDelay = TempFilesCleanerExecution.INTERVAL_TO_RUN_TMP_CLEAN_MS /* 1000 */)
    public void performCleanTempData() {
        tempDataCleanerExecution.execute();
    }

}

ScheduledTask é a minha própria interface com o meu método personalizado executar, o que eu chamo de minha tarefa agendada.

 5
Author: Yan Khonski, 2016-07-21 11:28:11

Estas duas classes podem trabalhar em conjunto para agendar uma tarefa periódica:

Tarefa Programada

import java.util.TimerTask;
import java.util.Date;

// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
    Date now; 
    public void run() {
        // Write code here that you want to execute periodically.
        now = new Date();                      // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

Executar Uma Tarefa Agendada

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {
        Timer time = new Timer();               // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
        //for demo only.
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread...." + i);
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

Referência https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

 5
Author: SumiSujith, 2018-12-31 20:57:22
Faz alguma coisa a cada segundo.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        //code
    }
}, 0, 1000);
 5
Author: Duchic, 2020-03-13 10:26:40

Se a sua aplicação já estiver a usar o 'Spring framework', você temescalonamento incorporado em

 4
Author: Black, 2014-10-14 22:25:57

Já tentouescalonamento de primavera usando anotações ?

@Scheduled(cron = "0 0 0/8 ? * * *")
public void scheduledMethodNoReturnValue(){
    //body can be another method call which returns some value.
}

Você pode fazer isso também com xml.

 <task:scheduled-tasks>
   <task:scheduled ref = "reference" method = "methodName" cron = "<cron expression here> -or- ${<cron expression from property files>}"
 <task:scheduled-tasks>
 3
Author: madhu_karnati, 2018-12-28 14:49:13

O meu servlet contém isto como um código de como manter isto no scheduler se um utilizador carregar em aceitar

if(bt.equals("accept")) {
    ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
    String lat=request.getParameter("latlocation");
    String lng=request.getParameter("lnglocation");
    requestingclass.updatelocation(lat,lng);
}
 0
Author: gopal krishna mareti, 2020-03-13 10:26:06